*(套接字编程)*客户端的C代码(通过UDP传递消息)在下面给出。我们可以通过
自动将端口号分配给套接字但是,使用getaddrinfo()函数执行相同操作时,将“ 0”(端口号)作为第二个参数传递会将端口0分配给套接字,而不分配任何USER_RESERVED端口。
如何使用getaddrinfo()实现自动端口分配?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netdb.h>
int main(int argc,char *argv[])
{
struct addrinfo client,*cl;
int status;
memset(&client,0,sizeof(client));//stucture should be empty
client.ai_family=AF_INET;
client.ai_socktype=SOCK_DGRAM;
client.ai_flags=AI_PASSIVE;
if(getaddrinfo(INADDR_ANY,"0",&client,&cl)!=0)
{
fprintf(stderr,"getaddrinfo: %s\n",gai_strerror(status));
return 2;
}
int s;
//printf("Port:: %d\n",((struct sockaddr_in*)(cl->ai_addr))->sin_port); //checking protocol number
s=socket(cl->ai_family,cl->ai_socktype,cl->ai_protocol);
//printf("Port:: %d\n",((struct sockaddr_in*)(cl->ai_addr))->sin_port); //checking protocol number
//bind(s,cl->ai_addr,cl->ai_addrlen);
//printf("Port:: %d\n",((struct sockaddr_in*)(cl->ai_addr))->sin_port); //checking protocol number
struct sockaddr_in server;
server.sin_family=AF_INET;
inet_pton(AF_INET,argv[1],&(server.sin_addr));
server.sin_port=htons(4169);
char str[100];
for(int i=2;i<argc;i++)
{
strncat(str,argv[i],strlen(argv[i]));
str[strlen(str)]=' ';
}
sendto(s,str,strlen(str),0,(struct sockaddr *)&server,(socklen_t)sizeof(server));
//printf("Port:: %d\n",((struct sockaddr_in*)(cl->ai_addr))->sin_port); //checking protocol number
close(s);
}