100_网络编程之IP地址函数

本文介绍了如何使用C语言中的网络函数进行IP地址的转换,包括从字符串到整数形式的转换,以及不同字节序之间的转换。通过具体示例代码演示了inet_addr(), inet_pton() 和 inet_ntop() 函数的用法。

inet_addr:字符串的192.168.0.102  转换成十进制的

inet_pton:能兼容IPCV6

inet_ntop


大小端的问题

网络字节序  统一使用大端模式

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

#define MYADDR  "192.168.0.188"


//0xbc   00   a8    c0
//188    0    168   192

int main(void)
{
	int addr = -1;
	
	addr = inet_addr(MYADDR);
	printf("addr = 0x%x.\n", addr);
	
	return 0;
}

n:就是net  是二进制的

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

#define MYADDR  "192.168.0.188"


//0xbc   00   a8    c0
//188    0    168   192

int main(void)
{
	int ret = 0;
	struct in_addr addr = {0};
	
	ret = inet_pton(AF_INET, MYADDR, &addr);
	
	printf("addr = 0x%x.\n", addr.s_addr);
	/*
	int addr = -1;
	
	addr = inet_addr(MYADDR);
	printf("addr = 0x%x.\n", addr);
	*/
	return 0;
}

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

#define MYADDR  "192.168.0.188"


//0xbc   00   a8    c0
//188    0    168   192

int main(void)
{
	struct in_addr addr = {0};
	addr.s_addr = 0xbc00a8c0;
	char buf[20] = {0};
	
	inet_ntop(AF_INET, &addr, buf, sizeof(buf));
	
	printf("addr = %s.\n", buf);
	
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值