Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Getting IP address in C (http://www.go4expert.com/forums/getting-ip-address-c-t22027/)

hraja 7May2010 07:29

Getting IP address in C
 
Hi,

I wish to get the system IP address in my C program. Unfortunately, when I tried the following code, I kept getting 127.0.1.1 and not the actual IP address of my system.

struct sockaddr_in server_addr;
struct hostent *host;
char hostname[256];

gethostname(hostname, sizeof(hostname));
host = gethostbyname(hostname);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
printf("IP address: %s\n", inet_ntoa(server_addr.sin_addr));


Thanks!

shabbir 7May2010 08:40

Re: Getting IP address in C
 
What is the string in your hostname?

shaju1981 7May2010 12:59

Re: Getting IP address in C
 
Quote:

Originally Posted by hraja (Post 67852)
Hi,

I wish to get the system IP address in my C program. Unfortunately, when I tried the following code, I kept getting 127.0.1.1 and not the actual IP address of my system.

struct sockaddr_in server_addr;
struct hostent *host;
char hostname[256];

gethostname(hostname, sizeof(hostname));
host = gethostbyname(hostname);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
printf("IP address: %s\n", inet_ntoa(server_addr.sin_addr));


Thanks!

Perform WSAstartup before calling any socket function

WORD wVersionRequested; WSADATA wsaData; int err;/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData);

Now it may work .... :-)


All times are GMT +5.5. The time now is 00:31.