• 修改后 简单的 UDP client


    /*
     ============================================================================
     Name        : UDPclient.c
     Author      : vestinfo
     Version     : 1.1
     Copyright   : www.cnblogs.com/vestinfo
     Description : A simple UDP client, Ansi-style
     ============================================================================
     */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    
    
    #define REMOTEPORT 8888
    #define REMOTEIP "127.0.0.1"
    
    #define CLIENT_PORT 9999
    #define CLIENT_IP "192.168.77.172"
    
    #define MAXLENGTH 256
    
    int main(int argc,char *argv[])
    {
    	int sockfd;
    	char msg[MAXLENGTH];
    	struct sockaddr_in servaddr;
    	struct sockaddr_in clientaddr;
    	socklen_t addr_len;
    	addr_len = sizeof(servaddr);
    
    	/* 创建数据报套接字 */
    	if(( sockfd = socket(AF_INET,SOCK_DGRAM,0))<0)
    	{
    		perror("error");
    		exit(1);
    	}
    
    	/* 绑定client的地址和端口,也可不绑定由内核指定 */
    	bzero(&clientaddr, sizeof(clientaddr));
    	clientaddr.sin_family = AF_INET;
    	clientaddr.sin_port = htons(CLIENT_PORT);
    	clientaddr.sin_addr.s_addr = inet_addr(CLIENT_IP);
    	if(bind(sockfd, (struct sockaddr *)&clientaddr, sizeof(clientaddr)) < 0)
    	{
    		perror("error");
    		exit(1);
    	}
    
    	/* server的地址结构 */
    	bzero(&servaddr,sizeof(servaddr));
    	servaddr.sin_family = AF_INET;
    	servaddr.sin_port = htons(REMOTEPORT);
    	servaddr.sin_addr.s_addr = inet_addr(REMOTEIP);
    
    	while(1)
    	{
    		bzero(msg, MAXLENGTH);
    		printf("please input msg\n");
    		read(STDIN_FILENO, msg, MAXLENGTH);													//从键盘(终端)键入msg
    
    		sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr *)&servaddr, addr_len);		//发送msg给目的套接字addr
    
    		recvfrom(sockfd, msg, MAXLENGTH, 0, (struct sockaddr *)&servaddr, &addr_len);	//接受目的套接字传来的msg
    		printf("Received message from server:%s\n",msg);
    	}
    
    }
    
    
  • 相关阅读:
    更新 anaconda
    spyder 每次运行前,清除上一次运行的变量
    vscode 无法使用 jupyter notebook
    vscode 关闭当前光标所在变量自动高亮
    vscode 关闭侧边栏中 git source control 的更改数目
    【java】Java组件概览(1)
    【java】字符串处理技巧记录
    【异常处理】Spring项目异常如何做异常处理
    【Springboot】Springboot学习(转)
    【微服务】微服务(转)
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2711506.html
Copyright © 2020-2023  润新知