Network Programming: Returning your ip (Linux)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    #1

    Network Programming: Returning your ip (Linux)

    Hello Bytes,

    To start I am running Debian Linux on x86.

    I am doing some network programing, Ive managed to create my UDP server that listens on a port for incoming packets.

    However my problem is that I catch my own broadcast packets which I do not want. I would like a way to check if the incoming packet is from my IP if so ignore it.

    So how do you return your ip in c/c++.

    Ill post how I create the socket:
    Code:
        int sockfd;
        struct addrinfo hints, *servinfo, *p;
        int rv;
        
    
        memset(&hints, 0, sizeof hints);
        hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_flags = AI_PASSIVE; // use my IP
    
        if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
            fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
            return 1;
        }
    
        // loop through all the results and bind to the first we can
        for (p = servinfo; p != NULL; p = p->ai_next) {
            if ((sockfd = socket(p->ai_family, p->ai_socktype,
                    p->ai_protocol)) == -1) {
                perror("udpServer: socket");
                continue;
            }
            
    
            if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
                close(sockfd);
                perror("udpServer: bind");
                continue;
            }
    
            break;
        }
    
    
        if (p == NULL) {
            fprintf(stderr, "udpServer: failed to bind socket\n");
            return 2;
        }
    
    
    
        struct timeval tv;
        tv.tv_sec = 2; /* 30 Secs Timeout */
        setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (struct timeval *) & tv, sizeof (struct timeval));
        
        freeaddrinfo(servinfo);
    Thanks in advance.
  • kardon33
    New Member
    • May 2007
    • 158

    #2
    I managed to figure it out, here is my solution.

    Code:
     #include <ifaddrs.h>
    
    
        struct ifaddrs * ifAddrStruct = NULL;
        void * tmpAddrPtr = NULL;
        char s[INET6_ADDRSTRLEN];
    
        getifaddrs(&ifAddrStruct);
        localAddress.clear();
    
        while (ifAddrStruct != NULL) {
            if (ifAddrStruct->ifa_addr->sa_family == AF_INET && strcmp(ifAddrStruct->ifa_name, "lo0") != 0) { // check it is IP4 and not lo0
                // is a valid IP4 Address
                tmpAddrPtr = &((struct sockaddr_in *) ifAddrStruct->ifa_addr)->sin_addr;
    
                inet_ntop(AF_INET, tmpAddrPtr, s, sizeof (s));
              
             
                printf("Address: %s \n",s);
               
            }
            ifAddrStruct = ifAddrStruct->ifa_next;
        }

    Comment

    Working...