Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to get my IP Address ?



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: http://lists.apple.com/mailman/options/darwin-dev/email@hidden

This email sent to email@hidden


Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.