python recvfrom函数详解_UDP sendto和recvfrom使用详解「建议收藏」

python recvfrom函数详解_UDP sendto和recvfrom使用详解「建议收藏」在网络编程中,UDP运用非常广泛。很多网络协议是基于UDP来实现的,如SNMP等。大家常常用到的局域网文件传输软件飞鸽传书也是基于UDP实现的。本篇文章跟大家分享linux下UDP的使用和实现,主要介绍下sendto()和recvfrom()两个函数的使用,以及INADDR_ANY的说明,并在最后展示了一个经过自己测试可用的UDPServer和UDPClient的代码示例。头文件#inclu…

大家好,又见面了,我是你们的朋友全栈君。



python recvfrom函数详解_UDP sendto和recvfrom使用详解「建议收藏」

在网络编程中,UDP运用非常广泛。很多网络协议是基于UDP来实现的,如SNMP等。大家常常用到的局域网文件传输软件飞鸽传书也是基于UDP实现的。

本篇文章跟大家分享linux下UDP的使用和实现,主要介绍下sendto()和recvfrom()两个函数的使用,以及INADDR_ANY的说明,并在最后展示了一个经过自己测试可用的UDP Server和UDP Client的代码示例。

头文件

#include

#include

函数原型

int sendto (int s, const void *buf, int len, unsigned int flags, const struct sockaddr *to, int tolen);

int recvfrom(int s, void *buf, int len, unsigned int flags, struct sockaddr *from, int *fromlen);

函数说明

sendto(),是把UDP数据报发给指定地址;recvfrom()是从指定地址接收UDP数据报。

参数说明

\s:              socket描述符。

\buf:         UDP数据报缓存地址。

\len:          UDP数据报长度。

\flags:       该参数一般为0。

\to:            sendto()函数参数,struct sockaddr_in类型,指明UDP数据发往哪里报。

\tolen:      对方地址长度,一般为:sizeof(struct sockaddr_in)。

\fromlen:recvfrom()函数参数,struct sockaddr_in类型,指明从哪里接收UDP数据报。

函数返回值

对于sendto()函数,成功则返回实际传送出去的字符数,失败返回-1,错误原因存于errno 中。

对于recvfrom()函数,成功则返回接收到的字符数,失败则返回-1,错误原因存于errno中。

struct sockaddr_in结构体

该结构体的定义如下:

/* Structure describing an Internet (IP) socket address. */

#define __SOCK_SIZE__16/* sizeof(struct sockaddr)*/

struct sockaddr_in {

sa_family_tsin_family;/* Address family*/

__be16sin_port;/* Port number*/

struct in_addrsin_addr;/* Internet address*/

/* Pad to size of `struct sockaddr’. */

unsigned char__pad[__SOCK_SIZE__ – sizeof(short int) –

sizeof(unsigned short int) – sizeof(struct in_addr)];

};

其中,sin_family指明地址族,一般使用AF_INET:

#define AF_INET2/* Internet IP Protocol */

sin_port:指明UDP端口;sin_addr指明IP地址:

/* Internet address. */

struct in_addr {

__be32s_addr;

};

INADDR_ANY说明

When you wrote your simple FTP server in project 1, you probably bound your listening socket to the special IP address INADDR_ANY. This allowed your program to work without knowing the IP address of the machine it was running on, or, in the case of a machine with multiple network interfaces, it allowed your server to receive packets destined to any of the interfaces. In reality, the semantics of INADDR_ANY are more complex and involved.

In the simulator, INADDR_ANY has the following semantics: When receiving, a socket bound to this address receives packets from all interfaces. For example, suppose that a host has interfaces 0, 1 and 2. If a UDP socket on this host is bound using INADDR_ANY and udp port 8000, then the socket will receive all packets for port 8000 that arrive on interfaces 0, 1, or 2. If a second socket attempts to Bind to port 8000 on interface 1, the Bind will fail since the first socket already “owns” that port/interface.

When sending, a socket bound with INADDR_ANY binds to the default IP address, which is that of the lowest-numbered interface.

大概的意思就是,作为接收端,当你调用bind()函数绑定IP时使用INADDR_ANY,表明接收来自任意IP、任意网卡的发给指定端口的数据。作为发送端,当用调用bind()函数绑定IP时使用INADDR_ANY,表明使用网卡号最低的网卡进行发送数据,也就是UDP数据广播。

关于UDP数据报

UDP都是以数据报的形式进行发送和接收的,而TCP是以数据流的形式进行发送和接收的。数据报和数据流,这两者要区分开来。

UDP Server和Client源码实例

UDP Server:

#include

#include

#include

#include

#include

#include

#include

#include

#defineUDP_TEST_PORT50001

int main(int argC, char* arg[])

{

struct sockaddr_in addr;

int sockfd, len = 0;

int addr_len = sizeof(struct sockaddr_in);

char buffer[256];

/* 建立socket,注意必须是SOCK_DGRAM */

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {

perror (“socket”);

exit(1);

}

/* 填写sockaddr_in 结构 */

bzero(&addr, sizeof(addr));

addr.sin_family = AF_INET;

addr.sin_port = htons(UDP_TEST_PORT);

addr.sin_addr.s_addr = htonl(INADDR_ANY) ;// 接收任意IP发来的数据

/* 绑定socket */

if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))<0) {

perror(“connect”);

exit(1);

}

while(1) {

bzero(buffer, sizeof(buffer));

len = recvfrom(sockfd, buffer, sizeof(buffer), 0,

(struct sockaddr *)&addr ,&addr_len);

/* 显示client端的网络地址和收到的字符串消息 */

printf(“Received a string from client %s, string is: %s\n”,

inet_ntoa(addr.sin_addr), buffer);

/* 将收到的字符串消息返回给client端 */

sendto(sockfd,buffer, len, 0, (struct sockaddr *)&addr, addr_len);

}

return 0;

}

// —————————————————————————-

// End of udp_server.c

UDP Client:

#include

#include

#include

#include

#include

#include

#include

#include

#defineUDP_TEST_PORT50001

#define UDP_SERVER_IP “127.0.0.1”

int main(int argC, char* arg[])

{

struct sockaddr_in addr;

int sockfd, len = 0;

int addr_len = sizeof(struct sockaddr_in);

char buffer[256];

/* 建立socket,注意必须是SOCK_DGRAM */

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {

perror(“socket”);

exit(1);

}

/* 填写sockaddr_in*/

bzero(&addr, sizeof(addr));

addr.sin_family = AF_INET;

addr.sin_port = htons(UDP_TEST_PORT);

addr.sin_addr.s_addr = inet_addr(UDP_SERVER_IP);

while(1) {

bzero(buffer, sizeof(buffer));

printf(“Please enter a string to send to server: \n”);

/* 从标准输入设备取得字符串*/

len = read(STDIN_FILENO, buffer, sizeof(buffer));

/* 将字符串传送给server端*/

sendto(sockfd, buffer, len, 0, (struct sockaddr *)&addr, addr_len);

/* 接收server端返回的字符串*/

len = recvfrom(sockfd, buffer, sizeof(buffer), 0,

(struct sockaddr *)&addr, &addr_len);

printf(“Receive from server: %s\n”, buffer);

}

return 0;

}

// —————————————————————————-

// End of udp_client.c

上述代码是经过验证可用的。

» 文章出处:

reille博客—http://velep.com

, 如果没有特别声明,文章均为reille博客原创作品

» 郑重声明:

原创作品未经允许不得转载,如需转载请联系reille#qq.com(#换成@)

分享到:

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/163421.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 5.6 读和写流

    5.6 读和写流

    2021年8月14日
    50
  • 【Java线程】锁机制:synchronized、Lock、Condition

    【Java线程】锁机制:synchronized、Lock、ConditionLock可以实现synchronized的相同功能,它能以更优雅的方式处理线程同步问题。与互斥锁定相比,读-写锁定允许对共享数据进行更高级别的并发访问。虽然一次只有一个线程(writer线程)可以修改共享数据,但在许多情况下,任何数量的线程可以同时读取共享数据(reader线程)Condition可以替代传统的线程间通信,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll()。Condition的强大之处在于它可以为多个线程间建

    2022年7月8日
    26
  • java phantomjs 截图_phantomjs 截图「建议收藏」

    java phantomjs 截图_phantomjs 截图「建议收藏」phantomjs截图,多个setTimeout是为了让页面尽量加载完整/**截图test.js**/varpage=require(‘webpage’).create();page.viewportSize={width:1024,height:600};page.open(‘http://www.2345.com/’,function(status){varbb=…

    2022年7月14日
    22
  • Maven–如何下载JSONObject相关依赖架包

    Maven–如何下载JSONObject相关依赖架包一、开发场景Java开发当中经常需要Json格式的数据,这就用到JSONObject类,本文章只提供以下两种JSONObject对应架包的下载方式。com.alibaba.fastjson.JSONObject(依赖1个架包fastjson-1.2.28.jar)net.sf.json.JSONObject(依赖6个架包commons-beanutils-1.9.3.jar、commons-c…

    2022年7月12日
    66
  • sqlyog下载安装_sqlyog激活成功教程版

    sqlyog下载安装_sqlyog激活成功教程版地址:https://github.com/webyog/sqlyog-community/wiki/Downloads

    2022年9月23日
    1
  • JavaScript数组-冒泡排序

    JavaScript数组-冒泡排序数组的冒泡排序算法也算一道经典面试题了,这里也给大家分享一下JavaScript中关于数组的冒泡排序的写法和思路:先给大家上代码:<script>//冒泡排序:将数组中的数字按照从大到小或从小到大的顺序排序vararr=[2,4,5,1,3];for(vari=0;i<arr.length-1;i++){//外层循环管趟数,即数组的全部项数都排好一共需要比较多少次一趟排好一个,注意趟

    2022年5月18日
    39

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号