• 大小: 5KB
    文件类型: .rar
    金币: 1
    下载: 0 次
    发布日期: 2021-05-22
  • 语言: 其他
  • 标签: Linux  聊天  UDP  协议  

资源简介

自己写的Linux下使用UDP协议的点对点聊天程序(含源代码),亲测可用,由于UDP的原理,不能确定对方是否上线,不保证对方收到也不能知道对方是否能收到消息

资源截图

代码片段和文件信息

/*first step in udp programming*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define BUFLEN 255
int main(int argcchar **argv)
{
struct sockaddr_in peeraddrlocaladdr;
int sockfd;
char recmsg[BUFLEN+1]pushmsg[BUFLEN+1];
int socklenn;
if(argc!=5){
printf(“%s    \n“argv[0]);
exit(0);
}

sockfd=socket(AF_INETSOCK_DGRAM0);
if(sockfd<0){
fprintf(stderr“socket creating error in udptalk.c!\n“);
exit(1);
}
socklen=sizeof(struct sockaddr);
memset(&peeraddr0socklen);
peeraddr.sin_family=AF_INET;
peeraddr.sin_port=htons(atoi(argv[2]));
if(inet_pton(AF_INETargv[1]&peeraddr.sin_addr)<=0){
printf(“Wrong dest IP address!\n“);
       exit(0); }

memset(&localaddr0socklen);
localaddr.sin_family=AF_INET;
localaddr.sin_port=htons(atoi(argv[4]));
if(inet_pton(AF_INETargv[3]&localaddr.sin_addr)<=0){
printf(“Wrong source IP address!\n“);
exit(0);
}

if(bind(sockfd(struct sockaddr *)(&localaddr)socklen)<0){
fprintf(stderr“bind local address error in udptalk.c!\n“);
exit(2);
}

fcntl(0F_SETFL O_NONBLOCK);
printf(“: “);
for(;;){
pushmsg[0]=0;
if(fgets(pushmsgBUFLENstdin)==“EOF“)exit(0);

if(pushmsg[0]!=0)if(sendto(sockfdpushmsgstrlen(pushmsg)0(struct sockaddr *)(&peeraddr)socklen)<0){
fprintf(stderr“sendto error in udptalk.c!\n“);
perror(““);
exit(3);
}else printf(“: “);

                n=recvfrom(sockfdrecmsgBUFLENMSG_DONTWAIT(struct sockaddr *)(&peeraddr)(socklen_t*)&socklen);
                if(n<0){
                        //fprintf(stderr“recvfrom error in udptalk.c\n“);
                        //perror(““);
                        //exit(4);
                }
                else{
                        recmsg[n]=0;
                        printf(“\n%s#%d>>>:        %s: “inet_ntoa(peeraddr.sin_addr)ntohs(peeraddr.sin_port)recmsg);
}
  }
}

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件        220  2013-06-09 13:01  #V1.00R130608-130609Linux UDP Talk(talk)\README.txt

     文件        220  2013-06-09 13:01  #V1.00R130608-130609Linux UDP Talk(talk)\README.txt~

     文件      10244  2013-06-09 12:45  #V1.00R130608-130609Linux UDP Talk(talk)\talk

     文件       2086  2013-06-09 12:45  #V1.00R130608-130609Linux UDP Talk(talk)\talk.cpp

     目录          0  2013-06-09 13:01  #V1.00R130608-130609Linux UDP Talk(talk)

----------- ---------  ---------- -----  ----

                12770                    5


评论

共有 条评论