首页 > 编程语言 >udp编程实例1

udp编程实例1

时间:2023-03-20 19:44:50浏览次数:62  
标签:sockaddr udp socket int 编程 clientaddr 实例 include struct

#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

int socket_fd;
void sig_fun(int signo)
{
    if(signo == SIGINT){
        printf("signo = %d\n",signo);
        close(socket_fd);
        exit(1);
    }
}

void out_addr(struct sockaddr_in *clientaddr)
{
    int port = ntohs(clientaddr->sin_port);
    
    char ip[16];
    
    if(inet_ntop(AF_INET, &clientaddr->sin_addr.s_addr, ip ,16) == NULL){
        perror("out_addr:");
    }
    
    printf("cliet:%s(%d)\n",ip,port);    

}

int main(int argc, char *argv[])
{
    if(argc < 2){
        printf("参数太少");
        exit(1);
    }
    
    if(signal(SIGINT,sig_fun) == SIG_ERR){
        perror("signal:");
        exit(1);
    }
    
    /*1. 创建socket*/
    if((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        perror("socket:");
        exit(1);
    }
    
    /*2. 绑定IP地址和端口号*/
    struct sockaddr_in serviceaddr;
    memset(&serviceaddr, 0, sizeof(serviceaddr));
    serviceaddr.sin_family = AF_INET;
    serviceaddr.sin_port = htons(atoi(argv[1]));
    serviceaddr.sin_addr.s_addr = INADDR_ANY;//一台服务器上可能有多块网卡(多个IP地址)
    //这个宏是响应本机所有网卡(IP地址)上连接的客户端请求
    
    if(bind(socket_fd, (struct sockaddr *)&serviceaddr, sizeof(serviceaddr)) < 0){
        perror("bind:");
        exit(1);
    }
    
    /*3. 读写*/
    //int recvfrom(int sockfd.void * buf,int len, unsigned int flags,struct sockaddr *from,int *fromlen);
    char buffer[512];
    memset(buffer, 0, sizeof(buffer));
    struct sockaddr_in clientaddr;
    int len = sizeof(clientaddr);
    if(recvfrom(socket_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientaddr, &len) < 0){
        printf("receive failed!\n");
    }
    out_addr(&clientaddr);
    
    //int sendto(int sockfd,const void*msg,int len,unsigned int flags,const struct sockaddr *to,int tolen);
    time_t curtime;
    time(&curtime);
    char *pts = ctime(&curtime);
    int length = strlen(pts);
    if(sendto(socket_fd, length + 1, 0, (struct sockaddr *)&clientaddr, &len) < 0){
        printf("sendto failed!\n");
    }
    
    
    return 0;
}

 

标签:sockaddr,udp,socket,int,编程,clientaddr,实例,include,struct
From: https://www.cnblogs.com/zj-studyrecoding/p/17237465.html

相关文章