花太多時間試圖弄清楚為什么inet_ntop總是2.0.19.86在我的準系統 C UDP 套接字程式內部回傳相同的 IP 地址。
這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define SERVERPORT "4950" // the port users will be connecting to
int main(int argc, char *argv[])
{
int sock;
struct addrinfo addr_type, *server_info, *p;
int err;
int numbytes;
if (argc != 3) {
fprintf(stderr,"usage: talker hostname message\n");
exit(1);
}
//Specify type of response we want to git
memset(&addr_type, 0, sizeof addr_type);
addr_type.ai_family = AF_INET; // set to AF_INET to use IPv4
addr_type.ai_socktype = SOCK_DGRAM;
//Get the address info (like IP address) and store in server_info struct
if ((err = getaddrinfo(argv[1], SERVERPORT, &addr_type, &server_info)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
return 1;
}
// There might be multiple IP addresses...loop through and use the first one that works
for(p = server_info; p != NULL; p = p->ai_next) {
if ((sock = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("Error when creating socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "Client failed to create socket\n");
return 2;
}
char s[INET_ADDRSTRLEN];
inet_ntop(AF_INET,(struct sockaddr_in *)p->ai_addr,s, sizeof s);
printf("sending to %s....\n",s);
if ((numbytes = sendto(sock, argv[2], strlen(argv[2]), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("Error sending message");
exit(1);
}
printf("client sent %d bytes to %s\n", numbytes, argv[1]);
freeaddrinfo(server_info);
close(sock);
return 0;
}
我特別堅持的路線是:
char s[INET_ADDRSTRLEN];
inet_ntop(AF_INET,(struct sockaddr_in *)p->ai_addr,s, sizeof s);
printf("sending to %s....\n",s);
例如,我運行程式./client www.google.com hello并獲得以下資訊:
sending to 2.0.19.86....
client sent 5 bytes to www.google.com
我再次運行該程式./client localhost hello,inet_ntop仍然回傳相同的 IP。
sending to 2.0.19.86....
client sent 5 bytes to localhost
創建套接字時沒有拋出任何錯誤,當我通過 localhost 將訊息發送到接收程式時,訊息發送成功,為什么 inet_ntop 仍然輸出這個奇怪的地址?
uj5u.com熱心網友回復:
在您致電inet_ntop:
inet_ntop(AF_INET,(struct sockaddr_in *)p->ai_addr,s, sizeof s);
您沒有傳遞正確的結構。當AF_INET作為第一個引數傳遞時,第二個引數應該是 type struct in_addr *,而不是struct sockaddr_in *。
您需要調出屬于sin_addr這種型別的成員。
inet_ntop(AF_INET, &((struct sockaddr_in *)p->ai_addr)->sin_addr, s, sizeof s);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426698.html
