我正在使用getaddrinfo()
编写一个小型服务器客户端程序。
而
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <mswsock.h>
#include <ws2tcpip.h>
char port[] = "1933";
char ip[] = "192.168.178.26";
int main() {
// Prolog - init socket
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,1), &wsaData) != 0) {
printf("- ERROR : WSAStartup() : %d", WSAGetLastError());
return 0;
}
int status;
SOCKET sock;
struct addrinfo *res = NULL;
struct addrinfo *p = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
status = getaddrinfo(ip, port, &hints, &res);
for ( p = res; p != NULL; p = p->ai_next ) {
printf("Before calling socket:\n\tres\t= %p\n\tp\t= %p\n", res, p);
// check all returned entries
if ( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 ) {
printf("- ERROR : socket() : ",
WSAGetLastError());
continue; }
printf("After calling socket:\n\tres\t= %p\n\tp\t= %p\n", res, p);
if ( connect(sock, p->ai_addr, p->ai_addrlen) == -1 ) {
printf("- ERROR : connect() : ",
WSAGetLastError());
continue; }
// socket was successfully connected
else {
printf("After calling connect:\n\tres\t= %p\n\tp\t= %p\n", res, p);
printf("+ SUCCESS : socket connected\n");
freeaddrinfo(res);
return sock; }
}
freeaddrinfo(res);
printf("- ERROR : socket could not be connected\n");
return 0;
}
工作正常,将struct addrinfo hints;
的位置更改为
int status;
SOCKET sock;
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p = NULL;
memset(&hints, 0, sizeof(hints));
创建套接字后,将导致意外行为。详细信息会在第一次调用*res
之后随机更改socket()
。
我使用 Codeblocks 和 GNU GCC编译器进行编码。
输出 version1 (正常工作):
Before calling socket:
res = 0049FBC8
p = 0049FBC8
After calling socket:
res = 0049FBC8
p = 0049FBC8
After calling connect:
res = 0049FBC8
p = 0049FBC8
+ SUCCESS : socket connected
输出 version2 (不工作):
Before calling socket:
res = 007DFBC8
p = 007DFBC8
After calling socket:
res = 00000002
p = 007DFBC8
After calling connect:
res = 0000007C
p = 007DFBC8
+ SUCCESS : socket connected