网络编程 day2

该程序创建了一个UDP套接字,绑定到指定端口,接收用户输入的文件名,向服务器发送请求。如果收到允许打开文件的响应,程序打开并写入接收到的数据,然后发送确认消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/stat.h>
#include<fcntl.h>
#define PORT 69
#define IP "192.168.2.144"
#define ERR_MSG(msg) do{\
    fprintf(stderr,"line:%d: %s %s",__LINE__,__FILE__,__func__);\
    perror(msg);\
}while(0)
int main()
{
    
    //创建套接字
    int soketfd=socket(AF_INET,SOCK_DGRAM,0);
    if(soketfd<0)
    {
        ERR_MSG("socket");
        return -1; 
    }
    struct sockaddr_in myaddr;
    myaddr.sin_family=AF_INET;
    myaddr.sin_port=htons(PORT);
    myaddr.sin_addr.s_addr=inet_addr(IP);
    //绑定端口与套字节 
    if(bind(soketfd,(struct sockaddr *)&myaddr,sizeof(myaddr))<0)
    {
        ERR_MSG("bind");
        return -1;
    }
    printf("bind success __%d__\n",__LINE__);
    char buf[516]="";
    char *sp1;
    short blok;
    printf("input the filename\n");
    scanf("%s",sp1);
    int size=sprintf(buf,"%c%c%s%c%s%c",0,1,sp1,0,"octet",0);
    if(sendto(soketfd,buf,size,0,(struct sockaddr *)&myaddr,size)<0)
    {
        ERR_MSG("SENDTO");
        return -1;
    }
    printf("send access __%d__",__LINE__);
   
    struct sockaddr_in cin;
    int addrlen=sizeof(cin);
    int myopen;
    if(recvfrom(soketfd,buf,size,0,(struct sockaddr *)&cin,&addrlen)<0)
    {
        ERR_MSG("RECSFROM");
        return -1;
    }
    if(buf[2]==5)
    {
        char *sp2=buf+4;
        printf("%s\n",sp2);
    }
    else if(buf[2]==3)
    {
        if(myopen==open("./test.txt",O_RDWR|O_APPEND|O_CREAT,0664))
        {
            ERR_MSG("OPEN");
            return -1;
        }
        while(buf)
        {
            write(myopen,buf,strlen(buf));
        }
        buf[0]=4;
        char ack[4];
        sprintf(ack,"%c%c%s",0,4,buf[2]);
        if(sendto(ack,buf,4,0,(struct sockaddr_in *)&cin,sizeof(cin))<0)
        {
            ERR_MSG("SENDTO");
            return -1;
        }
         close(myopen);
    }
    
    close(soketfd);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值