使用脚本通过套接字发送字符串

时间:2015-12-29 13:42:08

标签: python sockets

我正在使用一个用Python编写的程序,它接受用户通过socket输入的内容(我不在这里提供代码以免混淆,因为它可以通过传递类似于Hello world的字符串运行良好)。虽然我想要的是使用python传递一个大的String通过socket:

 $(python -c 'print "A" * 8000') 

和服务器读取8000次字母' A'不是上面的String作为输入。这怎么可能?

编辑:

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

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define KEYFILESIZE 41
#define BUFF_SIZE 0X1000
#define PORTNO    12345

void firstFunc(int FD){ 
  char buf[BUFF_SIZE];
  int cookie=*(int*)(buf+0x1000);
  printf("cookie: %x\n",cookie); //the server operator gets this info
  read(FD,buf,BUFF_SIZE*2); //overflow the buffer 2x
  return;
}

int servlet(int fd){
  char greetings[BUFF_SIZE];
  sprintf(greetings,"Greetings client #%d\n",fd);
  write(fd,greetings,strlen(greetings));
  firstFunc(fd);
  char* sorry="Sorry";
  write(fd,sorry,strlen(sorry));
  return 0;
}

int main(int argc, char *argv[])
{
  //char buffer[BUFFER_SIZE];
  int sockfd, newsockfd, portno, pid;
  socklen_t clilen;
  struct sockaddr_in serv_addr, cli_addr;

  /*  if (argc < 2) { */
  /*   fprintf(stderr,"ERROR, no port provided\n"); */
  /*   exit(1); */
  /* } */

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0){
    perror("ERROR opening socket");
    exit(1);
  }
  bzero((char *) &serv_addr, sizeof(serv_addr));
  //  portno = atoi(argv[1]);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(PORTNO);
  if (bind(sockfd, (struct sockaddr *) &serv_addr,
       sizeof(serv_addr)) < 0){
   perror("ERROR on binding");
   exit(1);
  }
  listen(sockfd,5);
  clilen = sizeof(cli_addr);
  while (1) {
    newsockfd = accept(sockfd,
               (struct sockaddr *) &cli_addr, &clilen);
    if (newsockfd < 0){
      perror("ERROR on accept");
      exit(1);
    }
    pid = fork();
    if (pid < 0){
      perror("ERROR on fork");
      exit(1);
    }
    if (pid == 0)  {
      close(sockfd);
      servlet(newsockfd);
      exit(0);
    }
    //make sure to wait at some point to avoid zombies
    else close(newsockfd);
    waitpid(-1, NULL, WNOHANG);
  }
  close(sockfd);
  return 0; 
}

好的,以上是在Ubuntu vm中运行的服务器的代码。使用netcat我从另一个vm(运行Kali)连接到服务器,我试图发送输入:
1. $(python -c 'print "A" * 8000')

  1. (python -c 'print "A" * 8000')
  2. 3。python -c 'print "A" * 8000'

    以上都没有奏效。下面是服务器在上述每个内容之后看到的图片 enter image description here

    当然,我希望在每种情况下看到的是8000&#39; A&#39; (AAAAAAAAAAAA ....)

1 个答案:

答案 0 :(得分:0)

这个问题的答案是在python中写一个文件,在建立连接之后(这是我用netcat手动完成的部分)将打印'A'的数字或任何所需的字符串。例如:

import socket
from struct import pack
host='ip_to_connect_to'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port_to_connect_to))
answer=s.recv(1024)
print answer
padding=800 * "A"

s.send(padding)