*(Socket programming)*C-code for client (passing messages through UDP) is given below. We can automatically assign port number to socket by
- not calling bind() before sendto() (related post)
- binding with port 0 (only provided in windows and solaris documentation for bind) that makes the kernel do automatic assignment.realted post
However doing the same with getaddrinfo() function,passing "0"(port number) as 2nd argument assigns port 0 to socket and not any USER_RESERVED port.
How to achieve automatic port assignment using 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);
}