C语言UDP socket编程

C语言UDP socket编程

UDP 服务器步骤如下:

  • 1.创建等链接套接字fd=socket()
  • 2.绑定待链接套接字bind(fd,服务器ip和端口)
  • 3.等待信息recvfrom(fd,对端地址)

UDP 客户端步骤如下:

  • 1.创建待连接套接字fd=scoket()
  • 2.发送信息sendto(fd,服务器ip和端口)

UDP服务器

int main(int argc, char const *argv[])
{
	// 创建一个UDP套接字
	int fd = Socket(AF_INET, SOCK_DGRAM, 0);

	struct sockaddr_in srvaddr;
	socklen_t len = sizeof(srvaddr);
	bzero(&srvaddr, len);

	srvaddr.sin_family = AF_INET;
	srvaddr.sin_port = htons(atoi(argv[1]));
	srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	// 绑定本地IP和端口
	Bind(fd, &srvaddr, len);

	// 迭代服务器
	char buf[SIZE];
	while(1)
	{
		bzero(buf, SIZE);
		recvfrom(fd, buf, SIZE, 0, NULL, NULL);

		printf("%s", buf);
	}

	return 0;
}

UDP客户端

int main(int argc, char const *argv[])
{
	// 创建一个UDP套接字
	int fd = Socket(AF_INET, SOCK_DGRAM, 0);

	struct sockaddr_in srvaddr;
	socklen_t len = sizeof(srvaddr);
	bzero(&srvaddr, len);

	srvaddr.sin_family = AF_INET;
	//srvaddr.sin_addr.s_addr = inet_addr("192.168.0.166");  
	inet_pton(AF_INET, arg[1], &srvaddr.sin_addr);
	srvaddr.sin_port = htons(atoi(argv[2]));


	char buf[SIZE];
	while(1)
	{
		bzero(buf, SIZE);
		fgets(buf, SIZE, stdin);

		sendto(fd, buf, strlen(buf), 0,
				(struct sockaddr *)&srvaddr, len);
	}

	return 0;
}

socket API做了如下封装


ssize_t Write(int fildes, const void *buf, size_t nbyte)
{
	ssize_t retval = write(fildes, buf, nbyte);
	if(retval == -1)
	{
		perror("write() error");
	}

	return retval;
}

ssize_t Read(int fildes, void *buf, size_t nbyte)
{
	int ret = read(fildes, buf, nbyte);
	if(ret == -1)
	{
		perror("read() failed");
	}
	return ret;
}

int Bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{
	int ret = bind(sockfd, addr, addrlen);
	if(ret == -1)
	{
		perror("bind() failed");
	}
	return ret;
}

int Listen(int sockfd, int backlog)
{
	int ret = listen(sockfd, backlog);
	if(ret == -1)
	{
		perror("listen() failed");
	}
	return ret;
}

int Accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
	int ret = accept(sockfd, addr, addrlen);
	if(ret == -1)
	{
		perror("accept() failed");
	}
	return ret;
}

int Connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{
	int ret = connect(sockfd, addr, addrlen);
	if(ret == -1)
	{
		perror("connect() failed");
	}
	return ret;
}

int Socket(int domain, int type, int protocol)
{
	int sockfd = socket(domain, type, protocol);
	if(sockfd == -1)
	{
		perror("socket() error");
	}

	return sockfd;
}

int Setsockopt(int sockfd, int level, int optname,
	       const void *optval, socklen_t optlen)
{
	int retval = setsockopt(sockfd, level, optname, optval, optlen);
	if(retval == -1)
	{
		perror("setsockopt() error");
	}

	return retval;
}

int Select(int nfds, fd_set *readfds, fd_set *writefds,
	   fd_set *exceptfds, struct timeval *timeout)
{
	int ret = select(nfds, readfds, writefds, exceptfds, timeout);
	if(ret == -1)
	{
		perror("select() failed");
	}
	return ret;
}

你可能感兴趣的:(网络编程)