栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

c语言网络通信客户端和服务器(udp)

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c语言网络通信客户端和服务器(udp)

客户端

#include 
#include 
#include  //读写分离就要包含线程相关的头文件
#include 
#include 
#include 
#include 

#define SERVPORT 5000

int main(int argc, char **argv)
{
    int ud, n;
    struct sockaddr_in ser, cli;
    char sendline[1000];
    char recvline[1000];

    if (argc != 2)
    {
        printf("usage: server address!n");
        exit(0);
    }

    ud = socket(AF_INET, SOCK_DGRAM, 0);
  

    bzero(&ser, sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_port = htons(SERVPORT);
    ser.sin_addr.s_addr = inet_addr(argv[1]);


    while (fgets(sendline, 1000, stdin))
    {

        sendto(ud, sendline, strlen(sendline), 0, (struct sockaddr *)&ser, sizeof(ser));

        n = recvfrom(ud, recvline, 1000, 0, NULL, NULL);

        recvline[n] = '';

        printf("********************************n");

        fputs(recvline, stdout);

        printf("********************************n");
    }

    close(ud);

    return 0;
}

服务器

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define SERVPORT 5000

int main()
{
    int ls, connfd, n;
    struct sockaddr_in ser, cli;
    socklen_t clilen;
    char msg[1000];

    ls = socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&ser, sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_port = htons(SERVPORT);
    ser.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(ls, (struct sockaddr *)&ser, sizeof(ser));


    while (1)  
    {
        clilen = sizeof(cli);

        n = recvfrom(ls, msg, 1000, 0, (struct sockaddr *)&cli, &clilen);
        
        sendto(ls, msg, n, 0, (struct sockaddr *)&cli, sizeof(cli));

        printf("--------------------------------n");
        printf("%s",cli);
        msg[n] = '';

        printf("--------------------------------------n");

        printf("%sn", msg);

        printf("--------------------------------------n");
        

    }

    close(ls);

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/296838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号