Translate IP address

Original story Original story 2

IP to int

static int toInt(int b0, int b1, int b2, int b3){
    int l = b0 << 24;
    l += b1 << 16;
    l += b2 << 8;
    l += b3;
    return l;
}

int to IP

static void printIPAddress(int i){
    int b0 = (i >> 24) & 0xff;
    int b1 = (i >> 16) & 0xff;
    int b2 = (i >> 8) & 0xff;
    int b3 = i & 0xff;
    System.out.printf("%d.%d.%d.%d%n", b0, b1, b2, b3);
}

Sample code

sample.c


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int
main(int argc, char *argv[])
{
 struct sockaddr_in server;
 int sock;
 char buf[32];
 char *deststr;
 int n;

 if (argc != 2) {
         printf("Usage : %s dest\n", argv[0]);
         return 1;
 }
 deststr = argv[1];

 sock = socket(AF_INET, SOCK_STREAM, 0);

 server.sin_family = AF_INET;
 server.sin_port = htons(12345);

 server.sin_addr.s_addr = inet_addr(deststr);
 if (server.sin_addr.s_addr == 0xffffffff) {
         struct hostent *host;

         host = gethostbyname(deststr);
         if (host == NULL) {
                 return 1;
         }
/*
         server.sin_addr.s_addr =
             *(unsigned int *)host->h_addr_list[0];
*/
         printf("%d\n", *(unsigned int *)host->h_addr_list[0]);
         printf("%d\n", *(unsigned int *)host->h_addr_list[1]);

         int i = 0;
         for(i = 0; i < 2; i++) {
          int ip1 = *(unsigned int *)host->h_addr_list[i];
          int b0 = (ip1 >> 24) & 0xff;
          int b1 = (ip1 >> 16) & 0xff;
          int b2 = (ip1 >> 8) & 0xff;
          int b3 = ip1 & 0xff;
          printf("%d.%d.%d.%d\n", b0, b1, b2, b3);
         }
 }
}

To check multi on in host.conf

Recommended Posts

Translate IP address
CentOS IP address Setup
Get country from IP address (Java)
IP address interfered with Docker bridge
IP address and port restrictions to Ubuntu