Re: How to get my IP Address ?
Re: How to get my IP Address ?
- Subject: Re: How to get my IP Address ?
- From: Noah Williamsson <email@hidden>
- Date: Tue, 30 Nov 2004 12:34:20 +0100
Hi Mark!
Mark Gilbert wrote:
Folks.
I have setup a very simple socket from one machine to another. I
want to send back very very simple HTML.
within the HTML I need to include my own IP address, but I am not
sure how to get it.
I tried gethostbyname("localhost"), but this returns 127.0.0.1 which
works on the local machine, but is not my address on the network.
Assuming you're using C and the BSD API you could use something like this.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
int main(int argc, char **argv) {
int s;
struct sockaddr_in sin;
int slen;
if(argc == 1) {
printf("Usage: %s <ip>\n", argv[0]);
return -1;
}
// Connect to port 80 somewhere
s = socket(PF_INET, SOCK_STREAM, 0);
memset(&sin, 0, sizeof(sin));
sin.sin_family = PF_INET;
sin.sin_port = htons(80);
sin.sin_addr.s_addr = inet_addr(argv[1]);
if(connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("connect()");
return -1;
}
// Get socket's local name
memset(&sin, 0, sizeof(sin));
slen = sizeof(sin);
if(getsockname(s, (struct sockaddr *)&sin, &slen) < 0) {
perror("getsockname()");
close(s);
return -1;
}
printf("Local IP is %s\n", inet_ntoa(sin.sin_addr));
// The local port is available in ntohs(sin.sin_port)
close(s);
return 0;
}
Here's a sample run:
insight$ ./1 127.0.0.1 # Use the loopback interface
Local IP is 127.0.0.1
insight$ ./1 216.239.59.99 # Google IP, will use external interface
Local IP is 194.18.12.187
insight$
As you can see, this code will show you the IP of the outgoing
interface, which may or may not be the IP the peer sees due to NAT, as
pointed out in other posts.
getsockname(3) will get you information about the local peer and
getpeername(3) will do the same, but for the remote peer.
-- noah
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden