日期:2014-05-16  浏览次数:20798 次

ubuntu下的c程序,关于无连接套接字通信的,求解!
功能是这样的,客户端给服务端发送消息,客户端把消息再返回给服务端,有两个程序,一个是客户端程序,一个是服务端程序,由于都在同一台机子,
所以服务端程序用的本地ip:127.0.0.1
程序不知道哪里出错了,研究不出来 麻烦前辈帮我看看,绝不是依赖,我真的努力了!感激阿

客户端程序:
C/C++ code
#include<stdio.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 4567
#define REMOTEIP "127.0.0.1"

void main()
{
    int s,len;
    struct sockaddr_in addr;
    int addr_len;
    char msg[256];
    int i=0;

    if((s=socket(AF_INET,SOCK_DGRAM,0))<0)
    {
        perror("error");
        exit(1);    
    }
    else
    {
        printf("socket created .\n");
        printf("socked id:%d\n",s);
        printf("remote ip:%s\n",REMOTEIP);
        printf("remote port:%d\n",REMOTEPORT);
    }
    
    len=sizeof(struct sockaddr_in);
    bzero(&addr,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_port=htons(REMOTEPORT);
    addr.sin_addr.s_addr=inet_addr(REMOTEIP);
    while(1)
    {
        bzero(msg,sizeof(msg));
        len=read(STDIN_FILENO,msg,sizeof(msg));
        sendto(s,msg,len,0,&addr,&addr_len);
        printf("\nInput message: %s",msg);
        len=recvfrom(s,msg,sizeof(msg),0,&addr,&addr_len);
        printf("%d:",i);
        i++;
        printf("Received message :%s",msg);
    }
}



服务端程序:
C/C++ code
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>

#define LOCALPORT 4567

void main()
{
    int mysock,len;
    struct sockaddr_in addr;
    int i=0;
    char msg[256];
    int addr_len;
    
    if((mysock=socket(AF_INET,SOCK_DGRAM,0))<0)
    {
        perror("error");
        exit(1);
    }
    else
    {
        printf("socket created .\n");
        printf("socked id :%d\n",mysock);
    }
    addr_len=sizeof(struct sockaddr_in);
    bzero(&addr,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_port=htons(LOCALPORT);
    addr.sin_addr.s_addr=htonl(INADDR_ANY);

    if(bind(mysock,&addr,sizeof(addr))<0)
    {
        perror("connect");
        exit(1);
    }
    else
    {
        printf("bind ok.\n");
        printf("local port :%d\n",LOCALPORT);
    }
    while(1)
    {
        bzero(msg,sizeof(msg));
        len=recvfrom(mysock,msg,sizeof(msg),0,&addr,&addr_len);
        printf("%d: ",i++);
        printf("message from :%s\n",inet_ntoa(addr.sin_addr));
        printf("message length : %d\n",len);
        printf("message:%s\n\n",msg);
        sendto(mysock,msg,len,0,&addr,addr_len);
    }
}






------解决方案--------------------
len=read(STDIN_FILENO,msg,sizeof(msg));
sendto(s,msg,len,0,&addr,&addr_len);

addr_len 没有赋值过。
------解决方案--------------------
客户端len=sizeof(struct sockaddr_in);

改成

addr_len = sizeof(struct sockaddr_in);

或者

addr_len = sizeof(addr);

------解决方案--------------------
一楼回答有问题,UDP是不用accept的

3L正解,没测... 应该没问题吧