-2

I'm writing a didactic client-server game. I want when the server starts, it prints an inet address on the screen. I know a machine can have more than one inet address, but I need only one, and get it in a easy way.

edit: During the testing of the client-server interactions i use the address 127.0.0.1. Now i want to test the client-server interactions when the client is on an other machine through internet. To do this i have to get the ip address from the server program (i want that the server print on the screen an inet address) and give it to the client program. Sorry for the misurunderstanding.

optimusfrenk
  • 1,271
  • 2
  • 16
  • 34
  • 1
    Use this one, it's free: `127.0.0.1` – Cody Gray - on strike Jan 12 '12 at 15:46
  • Too bad, you'll have two at the very least: the abovementioned loopback address (which is only useful for local traffic though), and the physical NIC address (maybe more). You need to loop through all of them and pick the most likely one. – Piskvor left the building Jan 12 '12 at 15:47
  • 2
    When you `bind` the socket, instead of using a specific IP address use `INADDR_ANY`. Then your server will listen for connections on all interfaces (i.e. all IP addresses on the machine). – Some programmer dude Jan 12 '12 at 15:48
  • possible duplicate of [Can't obtain local IP using gethostbyname()](http://stackoverflow.com/questions/8106882/cant-obtain-local-ip-using-gethostbyname) – Robᵩ Jan 12 '12 at 16:03
  • Why is this question getting down-voted? Getting your own network address in C is not self explanatory, and plenty of ways of asking the question don't come up with good responses. – asc99c Jan 13 '12 at 00:28

1 Answers1

2

You need the gethostname and gethostbyname functions, and inet_ntoa to print it out:

struct hostent *HostEntPtr;
struct in_addr in;
char           Hostname[100];

gethostname( Hostname, sizeof(Hostname) );
HostEntPtr = gethostbyname( Hostname );

if ( HostEntPtr != NULL )
{
  memcpy( &in.s_addr, *HostEntPtr->h_addr_list, sizeof(in.s_addr) );
  printf( "%s\n", inet_ntoa(in) );
}

(assuming this is to get your local IP address).

EDIT : h_addr_list is an array of pointers. The above example gets the first one, but to see all, just iterate over the array:

int i = 0;
while( HostEntPtr->h_addr_list[i] != NULL )
{
  memcpy( &in.s_addr, HostEntPtr->h_addr_list[i], sizeof(in.s_addr) );
  printf( "%s\n", inet_ntoa(in) );
}
asc99c
  • 3,815
  • 3
  • 31
  • 54
  • mmm... this code return 127.0.1.1 – optimusfrenk Jan 12 '12 at 23:08
  • It depends how you set up /etc/hosts. I normally only assign names localhost / loopback to 127.0.0.1. The actual hostname I only put against real external addresses. I have edited my answer to loop the array - you could check and avoid 127.0.0.1 in your loop. – asc99c Jan 13 '12 at 00:24