• Linux基础——查看IP及port的简单实现


    需要注意,不同的机器,有的可能为大端字节序,有的可能为小端字节序。

    小端就是低位字节排放在内存的低地址端即该值的起始地址,高位字节排放在内存的高地址端。

    大端就是高位字节排放在内存的低地址端即该值的起始地址,低位字节排放在内存的高地址端。

    实现代码如下:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 #include <sys/socket.h>
     5 #include <netinet/in.h>
     6 #include <arpa/inet.h>
     7 #define IP "180.97.33.107"
     8 int my_aton(char * ip)
     9 {
    10     int arr[4];
    11     int i;
    12     sscanf(ip,"%d.%d.%d.%d",arr,arr+1,arr+2,arr+3);
    13     i=(arr[0]<<24)|(arr[1]<<16)|(arr[2]<<8)|arr[3];
    14     return i;
    15 }
    16 char* my_ntoa(int i)
    17 {
    18     static char buf[1024];
    19     memset(buf,0,1024);
    20     sprintf(buf,"%d.%d.%d.%d",(i>>24)&0xff,(i>>16)&0xff,(i>>8)&0xff,i&0xff);
    21     return buf;
    22 }
    23 int main(int argc,char *argv[])
    24 {
    25     int i;
    26     i=my_aton(IP);
    27     struct in_addr my_add;
    28     inet_aton(IP,&my_add);
    29     printf("%x
    ",i);
    30     printf("%x
    ",my_add.s_addr);
    31     char *buf;
    32     buf=my_ntoa(i);
    33     printf("%s
    ",buf);
    34     printf("%s
    ",inet_ntoa(my_add));
    35 }
    View Code

    获得本地的IP方法如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    int main(int argc,char *argv[])
    {
        struct hostent *p;
        p=gethostbyname(argv[1]);
        char **pp;
        printf("name : %s
    ",p->h_name);
        pp=p->h_aliases;
        for(;*pp!=NULL;*pp++)
            printf("alia : %s
    ",*pp);
        printf("type : %d
    ",p->h_addrtype);
        printf("ip length : %d
    ",p->h_length);
        pp=p->h_addr_list;
        for(;*pp != NULL;*pp++)
            printf("ip : %s
    ",inet_ntoa(*(struct in_addr*)*pp));
        return 0;
    }
    View Code
  • 相关阅读:
    Selenium 中ExpectedConditions 用法说明(最全整理)
    logback的使用和logback.xml详解
    彻底征服 Spring AOP 之 实战篇
    彻底征服 Spring AOP 之 理论篇
    面试
    Java面试
    Python的数据类型与数据结构
    利用Python的 counter内置函数,统计文本中的单词数量
    python爬虫Urllib实战
    python爬虫实战一(基于正则表达式学习)
  • 原文地址:https://www.cnblogs.com/gjn135120/p/4009319.html
Copyright © 2020-2023  润新知