简单socket连接,tcp,备用

SOCKET Connect(CHAR* lpText, USHORT uPort)
{
	SOCKET s;

	s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (s != INVALID_SOCKET)
	{
		CHAR szIp[32] = {0};
		sockaddr_in sa;

		if (inet_addr(lpText) == INADDR_NONE)
		{
			if (struct hostent *hp = gethostbyname(lpText))
			{
				in_addr ia;

				CopyMemory(&ia, hp->h_addr, hp->h_length);
				lstrcpyA(szIp, inet_ntoa(ia));
			}
		}
		else
		{
			lstrcpyA(szIp, lpText);
		}
		sa.sin_family = AF_INET;
		sa.sin_port = htons(uPort);
		sa.sin_addr.s_addr = inet_addr(szIp);

		if (connect(s, (sockaddr*)&sa, sizeof(sa)) != 0)
		{
			closesocket(s);
			s = INVALID_SOCKET;
		}
	}
	return s;
}

你可能感兴趣的:(简单socket连接,tcp,备用)