编写客户端程序时出现编译错误

时间:2014-11-21 10:58:30

标签: c sockets

我是 新的 来进行套接字编程。我查看了Tutorialspoint中的一个程序。我对程序做了一些改动但是在编译时我遇到了错误。我我附上了一个告诉错误的图片。enter image description here

另外,我不明白什么是sin_family和sin_port.Shall我分别用serv_addr_family和serv_addr_port替换它们?

#include <stdio.h>
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#define portno 5432

int main(int argc, char *argv[])
{
int sockfd,n;
const struct sockaddr_in serv_addr;
const struct hostent *server;

char buffer[256];

if (argc < 3) {
    fprintf(stderr,"usage %s hostname port\n", argv[0]);
    return;
}

server = gethostbyname(argv[1]);
if (server == NULL) {
    fprintf(stderr,"ERROR, no such host\n");
    return;
}

/* Create a socket point */
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(*server->h_addr, 
       (char *)&serv_addr.sin_addr,
            server->h_length);
serv_addr.sin_port = htons(portno);

sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
{
    perror("ERROR opening socket");
    return;
}    
/* Now connect to the server */
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
{
     perror("ERROR connecting");
     return;
}   
/* Now ask for a message from the user, this message
* will be read by server
*/
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
/* Send message to the server */
n = write(sockfd,buffer,strlen(buffer));
if (n < 0) 
{
     perror("ERROR writing to socket");
     return;
}
/* Now read server response */
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0) 
{
     perror("ERROR reading from socket");
     return;
}
printf("%s\n",buffer);
return 0;
}

2 个答案:

答案 0 :(得分:1)

你必须在struct之前删除const。 用于配置套接字。(port,ip,...)

int sockfd,n;
const struct sockaddr_in serv_addr;
const struct hostent *server;

int sockfd,n;
struct sockaddr_in serv_addr;
struct hostent *server;

答案 1 :(得分:0)

这里有几点需要纠正:

  1. 首先,

    const struct sockaddr_in serv_addr;
    

    您将无法修改serv_addr,因为它是只读
    因此,您可能需要删除const关键字。

  2. 纠正上述步骤。您仍将在以下语句中遇到未定义的行为。

     bcopy(*server->h_addr, (char *)&serv_addr.sin_addr, server->h_length);   
    

    更改为以下内容:

     bcopy(server->h_addr, (char *)&serv_addr.sin_addr, server->h_length);
    

    注意在第一个参数中删除*  尊重是不正确的  根据评论,我也建议使用类似memcpy的函数。

  3. 作为良好编码实践的一部分。始终以正确的返回类型返回 由于-Wreturn-type期望main返回,导致int

     Example Change: 
     if (server == NULL) {
         fprintf(stderr,"ERROR, no such host\n");
         return;
     }  
    

    return -1 可能