建立连接的程序然后打印出它在C中接收的数据(套接字)

时间:2017-10-26 18:58:12

标签: c sockets

所以我试图习惯套接字,因为我需要使用它们为即将开始的课程创建入侵检测程序。 我现在尝试做的事情只是设置套接字文件描述符,将其绑定到一个地址,让它监听任何传入的请求,接受它们然后将它们写入文件。

我现在遇到的问题是,虽然我认为我在这里所做的是正确的,但我有点迷失方向,超过了listen()调用。我试图解决这个问题并查看功能,但目前还没有点击。在过去的6个小时里,我一直在这里,而且我已经走到了尽头。 此代码导致分段错误,无疑是由尝试从连接流写入输出流引起的。

我非常欣赏的两件主要事情:
A)我目前对发生的事情的理解(通过评论显示)是否正确? B)如果有人能够帮助我解决分段错误,或建议在建立一个非常好的文件后建立更好的方式来获取数据。

#include <stdio.h>
#include <stdlib.h>

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

#define MYPORT 3490
#define BACKLOG 10
int main(void)
{
  int sockfd = (AF_INET, SOCK_STREAM, 0);
    //creates socket file descriptor

  struct sockaddr_in servaddr;
    // creates sockaddr_in structure

  memset(&servaddr, 0, sizeof(servaddr));
    //zeros out values in servaddr

  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(MYPORT);
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    //sets contraints for servaddr

  bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    //binds sockfd socket file descriptor to a sockaddr pointer pointing to
    //memory location of our sockaddr_in servaddr

  listen(sockfd, BACKLOG);
    //listen for incoming connections

  struct sockaddr their_addr;
  socklen_t addr_size;
  int new_fd;
    //initialise sockaddr to store connector/clients socket address
    //create socklen_t (dont know what this is) for the size of their socket
    //new_fd for a new socket

  addr_size = sizeof(their_addr);
  new_fd = accept(sockfd, (struct sockaddr*) &their_addr, &addr_size );
    //set the new socket equal to the result of our accept()
    //accept takes the first connection queued on the host socket, pointer 
    //to a sockaddr where the connecting socket will be returned and 
    //the size of the structure to be allocated

  FILE * conn_f = fdopen(new_fd, "w+");
  FILE * output_f = fopen("receiver.txt", "w+");
  //Here I try and set up two streams.
  //One connection stream - conn_f which takes input from our new socket
  //One output stream output_f - which writes to a text file

  char *line = NULL;
  size_t len = 0;
  ssize_t bytes;

  while ((bytes = getline(&line, &len, conn_f)) != -1) {
    printf("Retrieved line of length %zu : %s\n", bytes, line);
    fwrite(line, sizeof(char), bytes, output_f);
  }
  free(line);
  //This was my attempt at reading the input line by line from my connection
  //stream, (conn_f) and writing it to my output stream (output_f)
  //I think this is causing the seg fault ^^

  close(conn_f);
  close(output_f);

  return 0;
}

0 个答案:

没有答案