字节序转换&IP地址转换接口


数据经过网络传输就需要考虑字节序的问题,经常常需要针对网络字节序(大端)和主机字节序进行转换。

1.字节序转换接口:

//man  hton 可查看
#include <arpa/inet.h>
h:host    n: net

uint32_t htonl(uint32_t hostlong);	32位(4字节)主机字节序到网络字节序的转换。
uint16_t htons(uint16_t hostshort);	16位主机字节序到网络字节序的转换   
uint32_t ntohl(uint32_t netlong); 	32网络字节序到位主机字节序转换
uint16_t ntohs(uint16_t netshort);	16位网络字节序到位主机字节序转换    

//上面这些接口里面能判断主机字节序,若与要转换的相同则不操作返回。

2.字符串点分十进制IP地址转换为网络字节序整数IP地址接口:

eg:192.168.2.2-转为十进制数字地址0xcoa80202

#include <sys/socket.h>  //socket接口头文件
#include <netinet/in.h>  //地址结构,协议类型头文件
#include <arpa/inet.h>   //字节序转换接口头文件

in_addr_t inet_addr(const char *cp);只能转换IPV4的ip地址
eg: addr.sin_addr.s_addr = inet_addr("172.17.0.3");

//int inet_pton(int af, const char *src, void *dst); IPV4,ipv6都能转换。

3.将网络IP地址转换为字符串点分十进制IP地址:

char *inet_ntoa(struct in_addr in); 只能转换IPV4的ip地址
//const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);IPV4,ipv6都能转换。
IPV4,ipv6都能转换。

Eg:

 bool Accept(TcpSocket *sock, 
                std::string *ip = NULL,uint16_t *port = NULL){
            //int accept(监听描述符,获取客户端地址,长度)
            struct sockaddr_in addr;
            socklen_t len = sizeof(struct sockaddr_in);
            int newfd = accept(_sockfd,(sockaddr*)&addr,&len);
            if (newfd < 0) {
                perror("accept error");
                return false;
            }
            sock->_sockfd = newfd;
            if (ip != NULL) {
                *ip = inet_ntoa(addr.sin_addr);
            }
            if (port != NULL) {
                *port = ntohs(addr.sin_port);
            }
            return true;
        }

常用命令

netstat -anptu 可查看当前主机上网络状态信息

 命令: netstat      
      	-a  查看所有网络信息
		-n   不显示服务名称,显示地址信息	
		-P  显示服务进程
		-t  过滤,只包含TCP
		-u  过滤,只包含udp

Ifconfig 可查看地址信息
云服务器–>内网地址:
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值