无法获取客户端通过TCP发送的消息

时间:2019-01-07 13:16:27

标签: c linux sockets netcat

我用C \ C ++编写了一个客户端,并向正在使用nc -l -p 6666进行监听的本地计算机发送了一条消息。
发送邮件后,本地主机上的nc没有任何问题。

我想问题出在我的代码中,但是我不确定哪一行。

为什么我没有收到任何与nc相关的消息?

代码:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h> 
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[]) {

  //http://www.linuxhowtos.org/C_C++/socket.htm

  int sockfd, portno, n;
  struct sockaddr_in serv_addr;
  struct hostent *server;
  const char ip[] = "127.0.0.1";
  char buffer[256];

  portno = atoi("6666");
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    error("ERROR opening socket");
  }
/*
  server = gethostbyname(argv[1]);

  if (server == NULL) {
      fprintf(stderr,"ERROR, no such host\n");
      exit(0);
  }

  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  bcopy((char *)server->h_addr, 
       (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
*/
  inet_aton(ip, &serv_addr.sin_addr);

  serv_addr.sin_port = htons(portno);
  if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ 
      error("ERROR connecting");
  }

  printf("Please enter the message: ");
  bzero(buffer,256);
  fgets(buffer,255,stdin);
   n = write(sockfd,buffer,strlen(buffer));
    if (n < 0) 
         error("ERROR writing to socket");
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0) 
         error("ERROR reading from socket");
    printf("%s\n",buffer);
    close(sockfd);
  return(0);
}

1 个答案:

答案 0 :(得分:3)

There are three parts to a sockaddr_in:

  • Host
    You set this with inet_aton (assuming the call succeeded; best add some error checking!)
  • Port
    You set this with serv_addr.sin_port = htons(portno);
  • Family
    Should be AF_INET in your case but, oops, you commented this out!

Everything else looks fine.