Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法获取客户端通过TCP发送的消息_C_Linux_Sockets_Netcat - Fatal编程技术网

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

无法获取客户端通过TCP发送的消息,c,linux,sockets,netcat,C,Linux,Sockets,Netcat,我用C\C++编写了一个客户端,并向本地机器发送了一条消息,该机器正在使用nc-l-P6666进行侦听。 发送消息后,我的本地主机上的nc未捕获任何内容 我想问题出在我的代码中,但我不确定是哪一行 为什么我没有收到nc的任何消息 代码: #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <string.h> #

我用C\C++编写了一个客户端,并向本地机器发送了一条消息,该机器正在使用nc-l-P6666进行侦听。 发送消息后,我的本地主机上的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);
}

sockaddr_由三部分组成:

主办 假设调用成功,则使用inet_aton设置此选项;最好添加一些错误检查! 港口城市 您可以使用serv_addr.sin_port=htonsportno; 家庭 在你的情况下应该是很好的,但是,哎呀,你把这个注释掉了!
其他一切看起来都很好。

sin_family未设置,该部分已注释掉。@SamVarshavchik谢谢@SamVarshavchik把它写下来作为答案,我会标记它,我们将结束这个问题。谢谢,这就是问题所在