-1

I have two socket file descriptors, a and b, which returned by function of socket. The question is: How can I do so that anything read from a would be written to b and, however, anything read from b would be written to a. This situation like proxy a little. would you give me some ideas, thanks!

  int fd_a, fd_b;

  void fd_init()
  {
    fd_a = socket(AF_INET, SOCK_STREAM, 0);
    fd_b = socket(AF_INET, SOCK_STREAM, 0); 
  }

  void* work_a(void* arg)
  {
    // read something from fd_a then write immediately to fd_b
  }

  void* work_b(void* arg)
  {
    // read something from fd_b then write immediately to fd_a
  }

  int main(int argc, char* argv[])
  {
    // ...
    fd_init();
    pthread_create(pthread_a, 0, work_a, NULL);
    pthread_create(phtread_b, 0, work_b, NULL);
    pthread_join(pthread_a);
    pthread_join(pthread_b);
    // ...
    return EXIT_SUCCESS;
  }

NOTE: CAN'T USE BUFFER ARRAY IN EITHER function of work_a() or function of work_b()

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anudorannador
  • 189
  • 1
  • 1
  • 11
  • 3
    Its best if you can add sample code on what you are trying to achieve. – askb Dec 30 '14 at 08:13
  • "...anything read from `a`..." - *Anything* ? A tall order if the reader(s) is/are blissfully unaware you're doing this, a condition suspiciously omitted from your description. It sounds like you're trying to implement a single-feature `ncat`, or `netcat`, etc. programatically. – WhozCraig Dec 30 '14 at 08:19
  • What do you mean by "can't use buffer array in either..." ??? – Jean-Baptiste Yunès Dec 30 '14 at 09:49
  • As you can see in the **schwer**'s answer below, he uses a array `buf` as a buffer. I mean that if there is way of redirection without the `buf`. – Anudorannador Dec 31 '14 at 02:51

1 Answers1

0

I don't know about any efficient way to do this without a buffer, so here is an example without using separate threads and only one buffer. You could use the doRW function below from multiple threads, but only with one buffer per thread. Recv and send seem to be thread safe methods as discussed in "Are parallel calls to send/recv on the same socket valid?".

int fd_a, fd_b;

void fd_init()
{
    fd_a = socket(AF_INET, SOCK_STREAM, 0);
    fd_b = socket(AF_INET, SOCK_STREAM, 0); 
}
bool doRW(int a, int b, char* buf, int size){
    int len = recv(a, buf, size, 0);
    if(len == 0) return false; //disconnected
    else if(len > 0) send(b, buf, len, 0);
    return true;
}
int main(int argc, char* argv[])
{
    // ...
    fd_init();
    fcntl(fd_a, F_SETFL, O_NONBLOCK);
    fcntl(fd_b, F_SETFL, O_NONBLOCK);
    char* buf = malloc(2048);
    while(doRW(fd_a, fd_b, buf, 2048) && doRW(fd_b, fd_a, buf, 2048)) ;
    free(buf);
    return EXIT_SUCCESS;
}
Community
  • 1
  • 1
schwer
  • 279
  • 1
  • 2
  • 10