Connect to a socket
I want to connect to a server socket identified by :
- its IP address : X.Y.Z.W (decimal dotted notation) - and its TCP port : n I cannot use the usual: gethostbyname(); inet_ntoa(); sequence of instructions because I do not assume I know hosts according to their host names but according to their IP addresses. I need to provide the connect() system call with the proper arguments. int connect(int socket, const struct sockaddr * address, socklen_t address_len); Let us say I declare : struct sockaddr_in in; I do not know what to put in : in.in_addr.s_addr (which is an unsigned int representing the IP address in network byte order). Please help me. |
First, the normal sequence (where a hostname such as "www.google.com" is given) is not
Code:
gethostbyname() Code:
gethostbyname() Second, inet_ntoa() converts not from decimal-dotted format to four-byte network-ordered format, but the other way around. "n" stands for "network", and "a" stands for "ASCII". inet_ntoa() goes from network to ASCII. What you want instead is inet_aton(). Third, instead of using inet_aton() and inet_ntoa(), I strongly recommend you use inet_pton() and inet_ntop(). (The "p" stands for "presentation" format.) There are two reasons to do this.
Code:
#include <stdio.h> Finally, you'll notice in the source code that I used variable inxyz, not in as you had in your example. When choosing the name of a variable, it's always better to choose something that's not a substring of some other identifier. Why? Because if you use your text editor to search for all instances of variable in, for example, you'll also find many other uninteresting occurrences of "in". |
Thanks a lot to you :),
it is exactly what I was searching for and it works ;) Thanks for the code and the comments. Good day in Mariposa. |
All times are GMT -5. The time now is 09:13 PM. |