zoukankan      html  css  js  c++  java
  • linux c 网络编程:用域名获取IP地址或者用IP获取域名 网络地址转换成整型 主机字符顺序与网络字节顺序的转换

    用域名获取IP地址或者用IP获取域名
    #include<stdio.h>
    #include<sys/socket.h>
    #include<netdb.h>
    int main(int argc,char **aggv)
    {
            struct hostent *host;
            char hostname[]="www.163.com";
            char hostname2[]="www.baidu.com";
            struct in_addr in;
            struct sockaddr_in addr_in;
            int h_errno;
            char addr[]="202.108.249.216";
    
            if((host=gethostbyname(hostname))!=NULL)
                    {
                            memcpy(&addr_in.sin_addr.s_addr,host->h_addr,4);
                            in.s_addr=addr_in.sin_addr.s_addr;
                            printf("Domain name : %s 
    ",hostname);
                            printf("IP length is: %d 
    ",host->h_length);
                            printf("Type : %d 
    ",host->h_addrtype);
                            printf("IP : %s 
    ",inet_ntoa(in));
    
                    }
    
            if(((host=gethostbyaddr(addr,sizeof(addr),AF_INET)))!=(struct hostnet *)NULL)
            {
                    memcpy(&addr_in.sin_addr.s_addr,host->h_addr,4);
                            in.s_addr=addr_in.sin_addr.s_addr;
                            printf("
    ---------------------
    ");
                            printf("Domain name : %s 
    ",hostname);
                            printf("IP length is: %d 
    ",host->h_length);
                            printf("Type : %d 
    ",host->h_addrtype);
                            printf("IP : %s 
    ",inet_ntoa(in));
            }
            return 0;
    }




    #include<stdio.h>
    #include<netdb.h>
    #include<arpa/inet.h>
    int main()
    {
            int i ;
            for(i=0;i<6;i++)
            printf("%d  %s 
    ",i,hstrerror(i));//捕获错误编号
    
            char cp[]="192.168.0.84";
            printf("%ld
    ",inet_addr(cp));
    //将网络地址转换成整型
    struct in_addr ip; ip.s_addr=16885952; printf("%s ",inet_ntoa(ip));
    //将整型转换成网络地址
    long local; int port; local=123456; port=1024; printf("net: %d ",htonl(local));//主机字符顺序与网络字节顺序的转换 printf("net: %d ",htonl(port)); printf("local: %d ",ntohl(htonl(local))); printf("local: %d ",ntohl(htonl(port))); return 0;}

    
    



  • 相关阅读:
    用例失败重新运行
    pytest启动浏览器,失败用例截图
    解决pycharm问题:module 'pip' has no attribute 'main'
    pytest的HTML
    pytest 的 yield
    pytest的setup和teardown
    pytest的fixture和conftest
    pycharm运行pytest
    简单易用的MongoDB
    快速入门系列--CLR--02多线程
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/7210611.html
Copyright © 2011-2022 走看看