套接字连接失败

时间:2015-09-20 08:54:37

标签: c linux sockets ifconfig

我是socket编程和阅读Linux网络编程的初学者。我决定实现客户端 - 服务器连接,如本书所示。服务器程序在Ubuntu 14.04机器上运行,客户端代码从Mac机器运行。服务器代码如下

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>

const char message[] = "hello, world\n";

int main()
{
  int sock = 0;
  int port = 0;
  sock = socket(AF_INET, SOCK_STREAM, 0);

  if (sock == -1)
    fprintf(stderr, "failed\n");
  else
    printf("connection is establisshed\n");

  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_addr.s_addr = htonl(INADDR_ANY );
  server.sin_port = 3500;

  int status = bind(sock, (struct sockaddr*) &server, sizeof(server));
  if (status == 0)
    printf("connection completed\n");
  else
    printf("problem is encountered\n");

  status = listen(sock, 5);
  if (status == 0)
    printf("app is ready to work\n");
  else
  {
    printf("connection is failed\n");
    return 0;
  }

  while (1)
  {
    struct sockaddr_in client = { 0 };
    int sclient = 0;
    int len = sizeof(client);
    int childSocket = accept(sock, (struct sockaddr*) &client, &len);
    if (childSocket == -1)
    {
      printf("cannot accept connection\n");
      close(sock);
      break;
    }

    write(childSocket, message, strlen(message));

    close(childSocket);
  }

  return 0;
}

至于客户端,我写了以下代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>

int main(int argc, char* argv[])
{
  int sock = 0;
  int port = 0;
  struct sockaddr_in servaddr;
  sock = socket(AF_INET, SOCK_STREAM, 0);
  int status = 0;
  char buffer[256] = "";
  if (sock == -1)
  {
    printf("could not establish connection\n");
    exit(1);
  }

  port = 3500;
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = inet_addr(argv[1]);
  servaddr.sin_port = htons(port);
  status = connect(sock, (struct sockaddr*) &servaddr, sizeof(servaddr));
  if (status == 0)
    printf("connection is established successfully\n");
  else
  {
    printf("could not run the app\n");
    exit(1);
  }

  status = read(sock, buffer, sizeof(buffer));
  if (status > 0)
    printf("%d: %s", status, buffer);

  close(sock);

  return 0;
}

要获取客户端计算机的IP地址,我从终端运行ifconfig获取inet_addr 192.168.1.165值。现在,当我将该地址字符串作为命令行参数传递时,我收到应用程序未运行消息的消息。据我所知,我得到的地址有问题。那么问题是什么? 提前致谢

1 个答案:

答案 0 :(得分:6)

很可能服务器不会监听您假设的端口,即3500

要解决此问题,请更改此行:

server.sin_port=3500

server.sin_port = htons(3500);

(要监视哪个进程列出了哪个地址:您可能希望使用netstat命令行工具的端口。在您的情况下可能使用选项-a -p -n

同样在最近的系统上accept()期望指向socklen_t的指针作为最后一个参数,因此请更改此

int len=sizeof(client);

socklen_t len = sizeof client; /* sizeof is an operator, not a function¨*/