我想获取连接到服务器套接字的套接字的IP地址。我已经包含了我的代码。
sa_data不返回“xxx.xxx.xxx.xxx”类型的char [14]。相反,它返回[11][1][xxx][xxx][xxx][xxx][][][][][][][]...[]
。有人可以帮忙吗?
int InitialResult;
char SendMessage[1024];
char ReceiveMessage[1024];
WSADATA WSAData;
addrinfo Hints;
addrinfo *Result;
SOCKET ListenSocket;
SOCKET ClientSocket;
ZeroMemory(&Hints, sizeof(Hints));
Hints.ai_family = AF_INET;
Hints.ai_socktype = SOCK_STREAM;
Hints.ai_protocol = IPPROTO_TCP;
Hints.ai_flags = AI_PASSIVE;
while(1)
{
InitialResult = WSAStartup(MAKEWORD(2,2), &WSAData);
if (InitialResult != 0)
{
cout << "WSA start up failed.";
}
InitialResult = getaddrinfo(NULL, portnumber, &Hints, &Result);
if (InitialResult != 0)
{
cout << "Get address information failed.";
WSACleanup();
}
ListenSocket = socket(Result->ai_family, Result->ai_socktype, Result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
cout << "Socket initialization failed.";
WSACleanup();
}
InitialResult = bind(ListenSocket, Result->ai_addr, (int)Result->ai_addrlen);
if (InitialResult == SOCKET_ERROR)
{
cout << "Bind failed." << portnumber;
closesocket(ListenSocket);
ListenSocket = INVALID_SOCKET;
WSACleanup();
}
InitialResult = listen(ListenSocket, SOMAXCONN);
if (InitialResult == SOCKET_ERROR)
{
cout << "Listen failed." << portnumber;
closesocket(ListenSocket);
ListenSocket = INVALID_SOCKET;
WSACleanup();
}
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET)
{
cout << "Socket accept failed." << portnumber;
WSACleanup();
}
sockaddr test;
int a = sizeof(test);
cout << "getpeername() return value : " << getpeername(ClientSocket, &test, &a) << endl;
cout << "test.sa_data : " << test.sa_data;
StartReceive(ReceiveMessage, ClientSocket);
strcpy(SendMessage,"Congratulations!! You have successfully transfered some data to G DA.");
StartSend(SendMessage, ClientSocket);
StartSend(portnumber, ClientSocket);
InitialResult = shutdown(ClientSocket, SD_SEND);
if (InitialResult == SOCKET_ERROR)
{
cout << "Shut down failed." << portnumber;
closesocket(ClientSocket);
WSACleanup();
}
closesocket(ClientSocket);
closesocket(ListenSocket);
WSACleanup();
}
答案 0 :(得分:2)
accept(2)
的第二和第三个参数允许您在不额外调用getpeername(2)
的情况下获取该信息。然后,您需要使用inet_ntoa(3)
之类的内容将二进制地址转换为字符串表示。
答案 1 :(得分:1)
为什么您认为WSADATA
应该是char [14]
?这是一个struct
,如图所示在these docs。
顺便说一句,在您检查的各种错误情况下,您应该终止整个函数(例如使用return
),而您正在做的事情似乎只是在一些消息之后继续使用结构&amp; c已知无效...
修改:哦,我知道,当你说sa_data
时,你的意思是test.sa_data
,另一个答案解释了为什么它不是你所期望的。无论如何都要留下这个答案,因为至少第二段非常重要(并且仍然相关; - )。
答案 2 :(得分:0)
sa_data不返回char [14] 类型“xxx.xxx.xxx.xxx”
没有指定这样做,所以难怪它不会。
您需要查看sockaddr_in和sockaddr_in6。