代码如下:
- SOCKET Sock = INVALID_SOCKET; // Datagram window socket
- SOCKADDR_IN source_sin; // Source socket address
- WSADATA WSAData; // Contains details of the
- // Winsock implementation
- // Initialize Winsock.
- if (WSAStartup (MAKEWORD(1,1), &WSAData) != 0)
- {
- return FALSE;
- }
- // Create a datagram window socket, Sock.
- if ((Sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_IP)) == INVALID_SOCKET)
- {
- return FALSE;
- }
- // Fill out source socket's address information.
- ULONG ipaddress = inet_addr("192.168.0.101"); /* 远程 IP 地址 */
- source_sin.sin_family = AF_INET;
- source_sin.sin_port = 3389;
- source_sin.sin_addr.s_addr = ipaddress;
- // 连接远程TCP服务器
- int ret = connect(Sock, (struct sockaddr *)&source_sin, sizeof(source_sin));
我想使用WinCE检测远程计算机是否开放某个端口,但是ret老是返回0,这个是方法错误的吗。还有什么办法吗,谢谢!
如果你是服务器 要去监听客户端的,而如果是客户端,要去连接服务器的
下面是服务器连接客户端的代码,你可以参考
//创建连接
WSADATA wsa;
DWORD IDThread;
//网络初始化
CString m_RemoteHost = "192.168.0.11";
int m_RemotePort = 1001;
if (WSAStartup(MAKEWORD(1,1), &wsa) != 0) /* WinSock 初始化 */
{
// MessageBox(_T("加载套接字失败!"));
return;
}
m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /* 创建TCP套接字 */
if (m_Socket == INVALID_SOCKET)
{
WSACleanup();
// MessageBox(_T("创建套接字失败!"));
return;
}
// 初始化远程 IP 地址及端口
m_RemoteAddr.sin_family = AF_INET;
m_RemoteAddr.sin_port = htons(m_RemotePort); /* 远程端口地址 */
char charRemoteHost[255];
ZeroMemory(charRemoteHost, 255);
int len = m_RemoteHost.GetLength();
// 将 Unicode 字符串转换为字节
LPTSTR pStr = m_RemoteHost.GetBuffer(len);
WideCharToMultiByte(CP_ACP, 0, pStr, len, charRemoteHost, len, NULL, NULL);
DWORD ipaddress = inet_addr(charRemoteHost); /* 远程 IP 地址 */
m_RemoteAddr.sin_addr.s_addr = ipaddress;
int rr = connect(m_Socket, (struct sockaddr *)&m_RemoteAddr, sizeof(m_RemoteAddr));
if (rr == SOCKET_ERROR)
{
//MessageBox(_T("连接TCP服务器失败!"));
return;
}
//MessageBox(_T("连接TCP服务器成功!"));
你选择的UDP协议,就不应该用connect了。
你可以用bind测试看能否绑定到远程地址,间接判断远程端口是否开放。
if(bind(sock, (struct sockaddr *) &source_sin, sizeof (source_sin))==SOCKET_ERROR)
{
fprintf(stderr, "Bind failed: %d\r\n", WSAGetLastError());
return 0;
}
原来返回0是已经连接上了,-1才是没有连接上。晕了