May 18th, 2004 03:13 PM
getaddrinfo() help please
Hi, I am currently trying to write a program that takes two arguments from the command line. The first one is the IP address (xxx.xxx.xx.xx) or hostname (whatever.edu), the second argument is the port number. I am writing a simple TCP client/server application in C and want to be able to use either the numerical form of and address or the actual name. In order to convert a hostname to an address I will use getaddrinfo(). My problem comes with my second argument, since I want to use any port number and not the name of the service specified by well known ports.
Example: ./tcpclient it.abc.edu 12345
From: man getaddrinfo
As you can see the second argument is a string that identifies the service, I will not be implementing any service in well known ports. When getaddrinfo returns, it returns a pointer to a linked list of addrinfo structs. Within this structs there is a pointer to a socket address structure, which is filled by getaddrinfo. Is there anyway to overwrite the values pointed at by this pointer to a sockaddr structure?? Because then I could:
getaddrinfo(const char *nodename, const char *servname,
const struct addrinfo *hints, struct addrinfo **res);
Making the service argument NULL, and then somehow modifying the port value in the returned socket address structure.
getaddrinfo( address, NULL, &hints, &results);
And then make the proper calls to socket() and connect().
I hope its not too confusing
May 20th, 2004 12:37 AM
A quick google search would have done the trick:
If you look at the description part of the page, it says that the second argument is either a service name or a decimal port number. You should be able to simply do some error checking on argv to make sure that it's a number (probably doesn't really matter too much) and feed it into the function:
getaddrinfo(address, argv, &hints, &results);
May 20th, 2004 04:34 AM
Yep, that's it, the second argument can be a number. I don't recommend coding for long periods without taking breaks, coz then you get frustrated and don't see that your errors are simply fixed. That is exactly what happened to me here.