Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- C sockets - Blocked on select
- void main(int argc, char **argv) {
- int s1, s2, n, server_port, sc1, sc2, rv, rc, left_peer_port;
- int peer_port;
- fd_set writefds, readfds;
- struct timeval tv;
- struct hostent *server_info, *child_info, *left_peer_info;
- int start_flag = 0;
- struct sockaddr_in server, peer, incoming;
- char host_child[64];
- char *left_host = malloc(1);
- char *right_host = malloc(1);
- char buf1[256];
- char buf2[256];
- server_port = atoi(argv[2]);
- //speak to peer using this
- s2 = socket(AF_INET, SOCK_STREAM, 0);
- if (s2 < 0) {
- perror("socket:");
- exit(s2);
- }
- peer_port = server_port + 1;
- gethostname(host_child, sizeof host_child);
- child_info = gethostbyname(host_child);
- if (child_info == NULL) {
- fprintf(stderr, "%s: host not found (%s)n", argv[0], host_child);
- exit(1);
- }
- peer.sin_family = AF_INET;
- memcpy(&peer.sin_addr, child_info->h_addr_list[0], child_info->h_length);
- int changeport = 0;
- do {
- peer.sin_port = htons(peer_port);
- rc = bind(s2, (struct sockaddr *) &peer, sizeof(peer));
- if (rc < 0) {
- //perror("bind:");
- peer_port++;
- changeport = 1;
- //exit(rc);
- } else {
- changeport = 0;
- }
- } while (changeport == 1);
- if (listen(s2, 100) == -1) {
- perror("listen");
- exit(3);
- }
- //Now talk to server
- server_info = gethostbyname(argv[1]);
- if (server_info == NULL) {
- fprintf(stderr, "%s: host not foundn", argv[0]);
- exit(1);
- }
- // pretend we've connected both to a server at this point
- //speak to server using this
- s1 = socket(AF_INET, SOCK_STREAM, 0);
- if (s1 < 0) {
- perror("socket:");
- exit(s1);
- }
- server.sin_family = AF_INET;
- server.sin_port = htons(server_port);
- memcpy(&server.sin_addr, server_info->h_addr_list[0], server_info->h_length);
- //To talk to the server
- sc1 = connect(s1, (struct sockaddr *) &server, sizeof(server));
- if (sc1 < 0) {
- perror("connect:");
- exit(sc1);
- }
- int send_len;
- char *str = malloc(1);
- sprintf(str, "%d", peer_port);
- printf("nport-here=%sn", str);
- send_len = send(s1, str, strlen(str), 0);
- if (send_len != strlen(str)) {
- perror("send");
- exit(1);
- }
- int recv_len;
- char buf[100];
- int ref = 0;
- int recv_stage = 0;
- int start_id;
- recv_len = recv(s1, buf, 34, 0);
- if (recv_len < 0) {
- perror("recv");
- exit(1);
- }
- buf[recv_len] = '