-
一、UDP服务器
-
创建
-
1、socket --创建套接字
-
2、bind--绑定
-
3、recvfrom--等待接收数据(无连接)(TCP用recv(有连接的))
- #include <sys/types.h>
- #include <sys/socket.h>
- ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
- struct sockaddr *src_addr, socklen_t *addrlen);
-
功能:从sockfd指向的端点读取数据,如果sockfd所指向的端点没有数据则阻塞
-
参数:
- sockfd:socket创建的套接字
- buf : 接收数据的缓存区
- len :希望从sockfd里面读取len个字节的数据
- fiags :一般传0
- src_addr :用于保存发送方的IP地址
- addrlen:地址结构体的长度(需要计算出来)
-
返回值:
- >0 :实际从sockfd中读取到的字节数
- -1 :失败
-
-
功能代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <unistd.h>
#include <s