void *Switch_Control::TCP_Accept_Control_thread(void *arg) { Switch_Control *this0 = (Switch_Control*)arg; int BUFFER_SIZE = 4096; struct sockaddr_in s_addr; int sock; socklen_t addr_len; if ( (sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1) { perror("socket"); fflush(stderr); LOG_ERROR("ERROR SWM : Create Socket ERROR \n"); return NULL; } else printf("create socket.\n\r"); fflush(stdout); memset(&s_addr, 0, sizeof(struct sockaddr_in)); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(this0->m_iMsiPort); s_addr.sin_addr.s_addr = inet_addr(this0->SW_ip.c_str());//INADDR_ANY; int optval = 1; if ((setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(int))) == -1) { close(sock); LOG_ERROR("ERROR SWM : Set Socket ReUSED ERROR \n"); return NULL; } if ( (bind(sock, (struct sockaddr*)&s_addr, sizeof(s_addr))) == -1 ) { perror("bind"); fflush(stderr); LOG_ERROR("ERROR SWM : Bind Socket ERROR \n"); return NULL; }else printf("bind address to socket.\n\r"); fflush(stdout); if(listen(sock,10)<0) { perror("listen"); fflush(stderr); LOG_ERROR("ERROR SWM : Listen Socket ERROR \n"); return NULL; } int accept_fd = -1; struct sockaddr_in remote_addr; memset(&remote_addr,0,sizeof(remote_addr)); this0->m_MsiacceptSocket = -1; while( 1 ) { socklen_t sin_size = sizeof(struct sockaddr_in); if(( accept_fd = accept(sock,(struct sockaddr*) &remote_addr,&sin_size)) == -1 ) { printf( "Accept error!\n"); fflush(stdout); //continue; } printf("Received a connection from %s\n",(char*) inet_ntoa(remote_addr.sin_addr)); fflush(stdout); if(this0->m_MsiacceptSocket != -1) { //需要释放之前的链接 } this0->m_MsiacceptSocket = accept_fd; //将socket加入队列 pthread_mutex_lock(&this0->m_lockerQuesocket); this0->m_QueSokcet.push(accept_fd); pthread_mutex_unlock(&this0->m_lockerQuesocket); pthread_t tcp_recv_thread1; pthread_create(&tcp_recv_thread1, NULL, Parse_recv_MSI_thread, this0); pthread_detach(tcp_recv_thread1); } }
static int identd(char *username) { int sok, read_sok, len; char *p; char buf[256]; char outbuf[256]; struct sockaddr_in addr; sok = socket(AF_INET, SOCK_STREAM, 0); if (sok == INVALID_SOCKET) { free(username); return 0; } len = 1; setsockopt(sok, SOL_SOCKET, SO_REUSEADDR, (char *)&len, sizeof(len)); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(113); if (bind(sok, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) { closesocket(sok); free(username); return 0; } if (listen(sok, 1) == SOCKET_ERROR) { closesocket(sok); free(username); return 0; } len = sizeof(addr); read_sok = accept(sok, (struct sockaddr *)&addr, &len); closesocket(sok); if (read_sok == INVALID_SOCKET) { free(username); return 0; } identd_is_running = FALSE; snprintf(outbuf, sizeof(outbuf), "%%\tServicing ident request from %s\n", inet_ntoa(addr.sin_addr)); // PrintText (current_sess, outbuf); recv(read_sok, buf, sizeof(buf) - 1, 0); buf[sizeof(buf) - 1] = 0; /* ensure null termination */ p = strchr(buf, ','); if (p) { snprintf(outbuf, sizeof(outbuf) - 1, "%d, %d : USERID : UNIX : %s\r\n", atoi(buf), atoi(p + 1), username); outbuf[sizeof(outbuf) - 1] = 0; /* ensure null termination */ send(read_sok, outbuf, strlen(outbuf), 0); } sleep(1); closesocket(read_sok); free(username); return 0; }
int main(int argc, char **argv) { int i; int port = 0; int listen_socket[3] = { -1, -1, -1 }; int accept_socket; int dup_accept_socket; int connection_count = 1; int count; int on = 1; int timeout = 5; int initial_pause = 0, tfo = 0; int use_ipv4 = 1; int use_ipv6 = 1; int debug = 0; int na = 1; line *script = NULL; line *last = NULL; line *s; FILE *in, *out; int linebuf = 1; char *pidfile = NULL; char *sockname = NULL; unsigned char buffer[10240]; struct sockaddr_un sockun; /* don't use "sun" */ struct sockaddr_un sockun_accepted; int sockun_len = sizeof(sockun_accepted); #if HAVE_IPV6 struct sockaddr_in6 sin6; struct sockaddr_in6 accepted; struct in6_addr anyaddr6 = IN6ADDR_ANY_INIT ; #else struct sockaddr_in accepted; #endif /* Always need an IPv4 structure */ struct sockaddr_in sin4; int len = sizeof(accepted); /* Sort out the arguments */ if (argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) { printf("Usage: %s [options] port|socket [connection count]\n", argv[0]); puts("Options" "\n\t-d debug" "\n\t-i n n seconds initial delay" "\n\t-noipv4 disable ipv4" "\n\t-noipv6 disable ipv6" "\n\t-oP file write PID to file" "\n\t-t n n seconds timeout" "\n\t-tfo enable TCP Fast Open" ); exit(0); } while (na < argc && argv[na][0] == '-') { if (strcmp(argv[na], "-d") == 0) debug = 1; else if (strcmp(argv[na], "-tfo") == 0) tfo = 1; else if (strcmp(argv[na], "-t") == 0) { if (tmo_noerror = ((timeout = atoi(argv[++na])) < 0)) timeout = -timeout; } else if (strcmp(argv[na], "-i") == 0) initial_pause = atoi(argv[++na]); else if (strcmp(argv[na], "-noipv4") == 0) use_ipv4 = 0; else if (strcmp(argv[na], "-noipv6") == 0) use_ipv6 = 0; else if (strcmp(argv[na], "-oP") == 0) pidfile = argv[++na]; else { printf("server: unknown option %s, try -h or --help\n", argv[na]); exit(1); } na++; } if (!use_ipv4 && !use_ipv6) { printf("server: -noipv4 and -noipv6 cannot both be given\n"); exit(1); } if (na >= argc) { printf("server: no port number or socket name given\n"); exit(1); } if (argv[na][0] == '/') { sockname = argv[na]; unlink(sockname); /* in case left lying around */ } else port = atoi(argv[na]); na++; if (na < argc) connection_count = atoi(argv[na]); /* Initial pause (before creating listen sockets */ if (initial_pause > 0) { if (debug) printf("%ld: Inital pause of %d seconds\n", (long)time(NULL), initial_pause); else printf("Inital pause of %d seconds\n", initial_pause); while (initial_pause > 0) initial_pause = sleep(initial_pause); } /* Create sockets */ if (port == 0) /* Unix domain */ { if (debug) printf("%d: Creating Unix domain socket\n", time(NULL)); listen_socket[udn] = socket(PF_UNIX, SOCK_STREAM, 0); if (listen_socket[udn] < 0) { printf("Unix domain socket creation failed: %s\n", strerror(errno)); exit(1); } } else { #if HAVE_IPV6 if (use_ipv6) { if (debug) printf("Creating IPv6 socket\n"); listen_socket[v6n] = socket(AF_INET6, SOCK_STREAM, 0); if (listen_socket[v6n] < 0) { printf("IPv6 socket creation failed: %s\n", strerror(errno)); exit(1); } #if defined(TCP_FASTOPEN) && !defined(__APPLE__) if (tfo) { int backlog = 5; if (setsockopt(listen_socket[v6n], IPPROTO_TCP, TCP_FASTOPEN, &backlog, sizeof(backlog))) if (debug) printf("setsockopt TCP_FASTOPEN: %s\n", strerror(errno)); } #endif /* If this is an IPv6 wildcard socket, set IPV6_V6ONLY if that option is available. */ #ifdef IPV6_V6ONLY if (setsockopt(listen_socket[v6n], IPPROTO_IPV6, IPV6_V6ONLY, (char *)(&on), sizeof(on)) < 0) printf("Setting IPV6_V6ONLY on IPv6 wildcard " "socket failed (%s): carrying on without it\n", strerror(errno)); #endif /* IPV6_V6ONLY */ } #endif /* HAVE_IPV6 */ /* Create an IPv4 socket if required */ if (use_ipv4) { if (debug) printf("Creating IPv4 socket\n"); listen_socket[v4n] = socket(AF_INET, SOCK_STREAM, 0); if (listen_socket[v4n] < 0) { printf("IPv4 socket creation failed: %s\n", strerror(errno)); exit(1); } #if defined(TCP_FASTOPEN) && !defined(__APPLE__) if (tfo) { int backlog = 5; if (setsockopt(listen_socket[v4n], IPPROTO_TCP, TCP_FASTOPEN, &backlog, sizeof(backlog))) if (debug) printf("setsockopt TCP_FASTOPEN: %s\n", strerror(errno)); } #endif } } /* Set SO_REUSEADDR on the IP sockets so that the program can be restarted while a connection is being handled - this can happen as old connections lie around for a bit while crashed processes are tidied away. Without this, a connection will prevent reuse of the smtp port for listening. */ for (i = v6n; i <= v4n; i++) { if (listen_socket[i] >= 0 && setsockopt(listen_socket[i], SOL_SOCKET, SO_REUSEADDR, (char *)(&on), sizeof(on)) < 0) { printf("setting SO_REUSEADDR on socket failed: %s\n", strerror(errno)); exit(1); } } /* Now bind the sockets to the required port or path. If a path, ensure anyone can write to it. */ if (port == 0) { struct stat statbuf; sockun.sun_family = AF_UNIX; if (debug) printf("Binding Unix domain socket\n"); sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sockname); if (bind(listen_socket[udn], (struct sockaddr *)&sockun, sizeof(sockun)) < 0) { printf("Unix domain socket bind() failed: %s\n", strerror(errno)); exit(1); } (void)stat(sockname, &statbuf); if (debug) printf("Setting Unix domain socket mode: %0x\n", statbuf.st_mode | 0777); if (chmod(sockname, statbuf.st_mode | 0777) < 0) { printf("Unix domain socket chmod() failed: %s\n", strerror(errno)); exit(1); } } else { for (i = 0; i < skn; i++) { if (listen_socket[i] < 0) continue; /* For an IPv6 listen, use an IPv6 socket */ #if HAVE_IPV6 if (i == v6n) { memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); sin6.sin6_addr = anyaddr6; if (bind(listen_socket[i], (struct sockaddr *)&sin6, sizeof(sin6)) < 0) { printf("IPv6 socket bind(port %d) failed: %s\n", port, strerror(errno)); exit(1); } } else #endif /* For an IPv4 bind, use an IPv4 socket, even in an IPv6 world. If an IPv4 bind fails EADDRINUSE after IPv6 success, carry on, because it means the IPv6 socket will handle IPv4 connections. */ { memset(&sin4, 0, sizeof(sin4)); sin4.sin_family = AF_INET; sin4.sin_addr.s_addr = (S_ADDR_TYPE)INADDR_ANY; sin4.sin_port = htons(port); if (bind(listen_socket[i], (struct sockaddr *)&sin4, sizeof(sin4)) < 0) if (listen_socket[v6n] < 0 || errno != EADDRINUSE) { printf("IPv4 socket bind(port %d) failed: %s\n", port, strerror(errno)); exit(1); } else { close(listen_socket[i]); listen_socket[i] = -1; } } } } /* Start listening. If IPv4 fails EADDRINUSE after IPv6 succeeds, ignore the error because it means that the IPv6 socket will handle IPv4 connections. Don't output anything, because it will mess up the test output, which will be different for systems that do this and those that don't. */ for (i = 0; i <= skn; i++) if (listen_socket[i] >= 0) { if (listen(listen_socket[i], 5) < 0) if (i != v4n || listen_socket[v6n] < 0 || errno != EADDRINUSE) { printf("listen() failed: %s\n", strerror(errno)); exit(1); } #if defined(TCP_FASTOPEN) && defined(__APPLE__) if ( tfo && setsockopt(listen_socket[v4n], IPPROTO_TCP, TCP_FASTOPEN, &on, sizeof(on)) && debug) printf("setsockopt TCP_FASTOPEN: %s\n", strerror(errno)); #endif } if (pidfile) { FILE * p; if (!(p = fopen(pidfile, "w"))) { fprintf(stderr, "pidfile create failed: %s\n", strerror(errno)); exit(1); } fprintf(p, "%ld\n", (long)getpid()); fclose(p); } /* This program handles only a fixed number of connections, in sequence. Before waiting for the first connection, read the standard input, which contains the script of things to do. A line containing "++++" is treated as end of file. This is so that the Perl driving script doesn't have to close the pipe - because that would cause it to wait for this process, which it doesn't yet want to do. The driving script adds the "++++" automatically - it doesn't actually appear in the test script. Within lines we interpret \xNN and \\ groups */ while (fgets(CS buffer, sizeof(buffer), stdin) != NULL) { line *next; char * d; int n = (int)strlen(CS buffer); if (n > 1 && buffer[0] == '>' && buffer[1] == '>') linebuf = 0; while (n > 0 && isspace(buffer[n-1])) n--; buffer[n] = 0; if (strcmp(CS buffer, "++++") == 0) break; next = malloc(sizeof(line) + n); next->next = NULL; d = next->line; { char * s = CS buffer; do { char ch; char cl = *s; if (cl == '\\' && (cl = *++s) == 'x') { if ((ch = *++s - '0') > 9 && (ch -= 'A'-'9'-1) > 15) ch -= 'a'-'A'; if ((cl = *++s - '0') > 9 && (cl -= 'A'-'9'-1) > 15) cl -= 'a'-'A'; cl |= ch << 4; } *d++ = cl; } while (*s++); } next->len = d - next->line - 1; if (last == NULL) script = last = next; else last->next = next; last = next; } fclose(stdin); /* SIGALRM handler crashes out */ signal(SIGALRM, sigalrm_handler); /* s points to the current place in the script */ s = script; for (count = 0; count < connection_count; count++) { struct { int left; BOOL in_use; } content_length = { 0, FALSE }; alarm(timeout); if (port <= 0) { printf("Listening on %s ... ", sockname); fflush(stdout); accept_socket = accept(listen_socket[udn], (struct sockaddr *)&sockun_accepted, &sockun_len); } else { int lcount; int max_socket = 0; fd_set select_listen; printf("Listening on port %d ... ", port); fflush(stdout); FD_ZERO(&select_listen); for (i = 0; i < skn; i++) { if (listen_socket[i] >= 0) FD_SET(listen_socket[i], &select_listen); if (listen_socket[i] > max_socket) max_socket = listen_socket[i]; } if ((lcount = select(max_socket + 1, &select_listen, NULL, NULL, NULL)) < 0) { printf("Select failed\n"); fflush(stdout); continue; } accept_socket = -1; for (i = 0; i < skn; i++) if (listen_socket[i] > 0 && FD_ISSET(listen_socket[i], &select_listen)) { accept_socket = accept(listen_socket[i], (struct sockaddr *)&accepted, &len); FD_CLR(listen_socket[i], &select_listen); break; } } alarm(0); if (accept_socket < 0) { printf("accept() failed: %s\n", strerror(errno)); exit(1); } out = fdopen(accept_socket, "w"); dup_accept_socket = dup(accept_socket); if (port > 0) printf("\nConnection request from [%s]\n", host_ntoa(&accepted, CS buffer)); else { printf("\nConnection request\n"); /* Linux supports a feature for acquiring the peer's credentials, but it appears to be Linux-specific. This code is untested and unused, just saved here for reference. */ /**********-------------------- struct ucred cr; int cl=sizeof(cr); if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &cl)==0) { printf("Peer's pid=%d, uid=%d, gid=%d\n", cr.pid, cr.uid, cr.gid); --------------*****************/ } fflush(stdout); if (dup_accept_socket < 0) { printf("Couldn't dup socket descriptor\n"); printf("421 Connection refused: %s\n", strerror(errno)); fprintf(out, "421 Connection refused: %s\r\n", strerror(errno)); fclose(out); exit(2); } in = fdopen(dup_accept_socket, "r"); /* Loop for handling the conversation(s). For use in SMTP sessions, there are default rules for determining input and output lines: the latter start with digits. This means that the input looks like SMTP dialog. However, this doesn't work for other tests (e.g. ident tests) so we have explicit '<' and '>' flags for input and output as well as the defaults. */ for (; s; s = s->next) { char *ss = s->line; /* Output lines either start with '>' or a digit. In the '>' case we can fudge the sending of \r\n as required. Default is \r\n, ">>" send nothing, ">CR>" sends \r only, and ">LF>" sends \n only. We can also force a connection closedown by ">*eof". */ if (ss[0] == '>') { char *end = "\r\n"; unsigned len = s->len; printit(ss++, len--); if (strncmp(ss, "*eof", 4) == 0) { s = s->next; goto END_OFF; } if (*ss == '>') { end = ""; ss++; len--; } else if (strncmp(ss, "CR>", 3) == 0) { end = "\r"; ss += 3; len -= 3; } else if (strncmp(ss, "LF>", 3) == 0) { end = "\n"; ss += 3; len -= 3; } fwrite(ss, 1, len, out); if (*end) fprintf(out, end); } else if (isdigit((unsigned char)ss[0])) { printf("%s\n", ss); fprintf(out, "%s\r\n", ss); } /* If the script line starts with "*sleep" we just sleep for a while before continuing. */ else if (strncmp(ss, "*sleep ", 7) == 0) { int sleepfor = atoi(ss+7); printf("%s\n", ss); fflush(out); sleep(sleepfor); } /* If the script line starts with "*data " we expect a numeric argument, and we expect to read (and discard) that many data bytes from the input. */ else if (strncmp(ss, "*data ", 6) == 0) { int dlen = atoi(ss+6); int n; alarm(timeout); if (!linebuf) while (dlen > 0) { n = dlen < sizeof(buffer) ? dlen : sizeof(buffer); if ((n = read(dup_accept_socket, CS buffer, n)) == 0) { printf("Unexpected EOF read from client\n"); s = s->next; goto END_OFF; } dlen -= n; } else while (dlen-- > 0) if (fgetc(in) == EOF) { printf("Unexpected EOF read from client\n"); s = s->next; goto END_OFF; } } /* Otherwise the script line is the start of an input line we are expecting from the client, or "*eof" indicating we expect the client to close the connection. Read command line or data lines; the latter are indicated by the expected line being just ".". If the line starts with '<', that doesn't form part of the expected input. (This allows for incoming data starting with a digit.) If the line starts with '<<' we operate in unbuffered rather than line mode and assume that a single read gets the entire message. */ else { int offset; int data = strcmp(ss, ".") == 0; if (ss[0] != '<') offset = 0; else { buffer[0] = '<'; if (ss[1] != '<') offset = 1; else { buffer[1] = '<'; offset = 2; } } fflush(out); if (!linebuf) { int n; char c; alarm(timeout); n = read(dup_accept_socket, CS buffer+offset, s->len - offset); if (content_length.in_use) content_length.left -= n; if (n == 0) { printf("%sxpected EOF read from client\n", (strncmp(ss, "*eof", 4) == 0)? "E" : "Une"); s = s->next; goto END_OFF; } if (offset != 2) while (read(dup_accept_socket, &c, 1) == 1 && c != '\n') ; alarm(0); n += offset; printit(CS buffer, n); if (data) do { n = (read(dup_accept_socket, &c, 1) == 1 && c == '.'); if (content_length.in_use) content_length.left--; while (c != '\n' && read(dup_accept_socket, &c, 1) == 1) if (content_length.in_use) content_length.left--; } while (!n); else if (memcmp(ss, buffer, n) != 0) { printf("Comparison failed - bailing out\nExpected: "); printit(ss, n); break; } } else { for (;;) { int n; alarm(timeout); if (fgets(CS buffer+offset, sizeof(buffer)-offset, in) == NULL) { printf("%sxpected EOF read from client\n", (strncmp(ss, "*eof", 4) == 0)? "E" : "Une"); s = s->next; goto END_OFF; } alarm(0); n = strlen(CS buffer); if (content_length.in_use) content_length.left -= (n - offset); while (n > 0 && isspace(buffer[n-1])) n--; buffer[n] = 0; printf("%s\n", buffer); if (!data || strcmp(CS buffer, ".") == 0) break; } if (strncmp(ss, CS buffer, (int)strlen(ss)) != 0) { printf("Comparison failed - bailing out\n"); printf("Expected: %s\n", ss); break; } } if (sscanf(CCS buffer, "<Content-length: %d", &content_length.left)) content_length.in_use = TRUE; if (content_length.in_use && content_length.left <= 0) shutdown(dup_accept_socket, SHUT_RD); } } END_OFF: fclose(in); fclose(out); } if (s == NULL) printf("End of script\n"); if (sockname) unlink(sockname); exit(0); }
/* Send the contents of the global buffer via the non-multicast socket */ int /* <0 on failure */ output(enum output_type type, struct sockaddr_in *dst, /* send to here */ struct interface *ifp, struct rip *buf, int size) /* this many bytes */ { struct sockaddr_in osin; int flags; const char *msg; int res; int soc; int serrno; assert(ifp != NULL); osin = *dst; if (osin.sin_port == 0) osin.sin_port = htons(RIP_PORT); #ifdef _HAVE_SIN_LEN if (osin.sin_len == 0) osin.sin_len = sizeof(osin); #endif soc = rip_sock; flags = 0; switch (type) { case OUT_QUERY: msg = "Answer Query"; if (soc < 0) soc = ifp->int_rip_sock; break; case OUT_UNICAST: msg = "Send"; if (soc < 0) soc = ifp->int_rip_sock; flags = MSG_DONTROUTE; break; case OUT_BROADCAST: if (ifp->int_if_flags & IFF_POINTOPOINT) { msg = "Send"; } else { msg = "Send bcast"; } flags = MSG_DONTROUTE; break; case OUT_MULTICAST: if ((ifp->int_if_flags & (IFF_POINTOPOINT|IFF_MULTICAST)) == IFF_POINTOPOINT) { msg = "Send pt-to-pt"; } else if (ifp->int_state & IS_DUP) { trace_act("abort multicast output via %s" " with duplicate address", ifp->int_name); return 0; } else { msg = "Send mcast"; if (rip_sock_mcast != ifp) { struct ip_mreqn mreqn; memset(&mreqn, 0, sizeof(struct ip_mreqn)); mreqn.imr_ifindex = ifp->int_index; if (0 > setsockopt(rip_sock, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn))) { serrno = errno; LOGERR("setsockopt(rip_sock, " "IP_MULTICAST_IF)"); errno = serrno; ifp = NULL; return -1; } rip_sock_mcast = ifp; } osin.sin_addr.s_addr = htonl(INADDR_RIP_GROUP); } break; case NO_OUT_MULTICAST: case NO_OUT_RIPV2: default: #ifdef DEBUG abort(); #endif return -1; } trace_rip(msg, "to", &osin, ifp, buf, size); res = sendto(soc, buf, size, flags, (struct sockaddr *)&osin, sizeof(osin)); if (res < 0 && (ifp == NULL || !(ifp->int_state & IS_BROKE))) { serrno = errno; msglog("%s sendto(%s%s%s.%d): %s", msg, ifp != NULL ? ifp->int_name : "", ifp != NULL ? ", " : "", inet_ntoa(osin.sin_addr), ntohs(osin.sin_port), strerror(errno)); errno = serrno; } return res; }
struct DomainSocket *new_domain_socket(const char *path, int access_mask, void (*read_callback)(struct DSClient *client), void (*write_callback)(struct DSClient *client), void (*error_callback)(struct DSClient *client), int listen_backlog) { struct linger ling = {0, 0}; struct sockaddr_un addr; struct stat tstat; int flags = 1; int old_umask; struct DomainSocket *uds; assert(path != NULL); uds = malloc(sizeof(struct DomainSocket)); uds->path = strdup(path); uds->fd = -1; uds->read_callback = read_callback; uds->write_callback = write_callback; uds->error_callback = error_callback; if ((uds->fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { _DEBUG("%s: socket() failed\n", __FUNCTION__); free_domain_socket(uds); return NULL; } // clean up a previous socket file if we left it around if (lstat(path, &tstat) == 0) { if (S_ISSOCK(tstat.st_mode)) { unlink(path); } } // @jayridge doesn't think this does anything here setsockopt(uds->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); // @jayridge doesn't think this does anything here setsockopt(uds->fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); setsockopt(uds->fd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); // clears nonstandard fields in some impementations that otherwise mess things up memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); assert(strcmp(addr.sun_path, path) == 0); old_umask = umask(~(access_mask & 0777)); if (bind(uds->fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { _DEBUG("%s: bind() failed\n", __FUNCTION__); free_domain_socket(uds); umask(old_umask); return NULL; } umask(old_umask); if (listen(uds->fd, listen_backlog) == -1) { _DEBUG("%s: listen() failed\n", __FUNCTION__); free_domain_socket(uds); return NULL; } if (evutil_make_socket_nonblocking(uds->fd) == -1) { _DEBUG("%s: evutil_make_socket_nonblocking() failed\n", __FUNCTION__); free_domain_socket(uds); return NULL; } event_set(&uds->ev, uds->fd, EV_READ | EV_PERSIST, accept_socket, uds); if (event_add(&uds->ev, NULL) == -1) { _DEBUG("%s: event_add() failed\n", __FUNCTION__); free_domain_socket(uds); return NULL; } return uds; }
int _aol_getclientsocket(char *host, int port) { struct hostent *hp; int success, i, flag; register int s=-1; struct linger l; struct sockaddr_in sin; if(host==NULL || port==0) return(-1); if((hp=gethostbyname(host)) == NULL) { #ifdef HAVE_HERROR herror("gethostbyname"); #else fprintf(stderr, "Error looking up %s\n", host); #endif return(-1); } success=0; /* of course, replace that 1 with the max number of con attempts */ for(i=0; i<1; i++) { if((s=socket(AF_INET, SOCK_STREAM, 0))<0) { perror("socket"); return(-1); } sin.sin_family = AF_INET; sin.sin_port=htons(port); memcpy(&sin.sin_addr, hp->h_addr, hp->h_length); l.l_onoff = 1; l.l_linger = 60; setsockopt(s, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l)); flag=1; if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int)) <0) { puts("Nagle algorithm not dislabled."); } if(connect(s, (struct sockaddr *)&sin, sizeof(sin))<0) { sleep(1); } else { success=1; break; } } if(!success) s=-1; return(s); }
int socketOpenConnection(char *host, int port, socketAccept_t accept, int flags) { #if (!defined (NO_GETHOSTBYNAME) && !defined (VXWORKS)) struct hostent *hostent; /* Host database entry */ #endif /* ! (NO_GETHOSTBYNAME || VXWORKS) */ socket_t *sp; struct sockaddr_in sockaddr; int sid, bcast, dgram, rc; if (port > SOCKET_PORT_MAX) { return -1; } /* * Allocate a socket structure */ if ((sid = socketAlloc(host, port, accept, flags)) < 0) { return -1; } sp = socketList[sid]; a_assert(sp); /* * Create the socket address structure */ memset((char *) &sockaddr, '\0', sizeof(struct sockaddr_in)); sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons((short) (port & 0xFFFF)); if (host == NULL) { sockaddr.sin_addr.s_addr = INADDR_ANY; } else { sockaddr.sin_addr.s_addr = inet_addr(host); if (sockaddr.sin_addr.s_addr == INADDR_NONE) { /* * If the OS does not support gethostbyname functionality, the macro: * NO_GETHOSTBYNAME should be defined to skip the use of gethostbyname. * Unfortunatly there is no easy way to recover, the following code * simply uses the basicGetHost IP for the sockaddr. */ #ifdef NO_GETHOSTBYNAME if (strcmp(host, basicGetHost()) == 0) { sockaddr.sin_addr.s_addr = inet_addr(basicGetAddress()); } if (sockaddr.sin_addr.s_addr == INADDR_NONE) { socketFree(sid); return -1; } #elif (defined (VXWORKS)) sockaddr.sin_addr.s_addr = (unsigned long) hostGetByName(host); if (sockaddr.sin_addr.s_addr == NULL) { errno = ENXIO; socketFree(sid); return -1; } #else hostent = gethostbyname(host); if (hostent != NULL) { memcpy((char *) &sockaddr.sin_addr, (char *) hostent->h_addr_list[0], (size_t) hostent->h_length); } else { char *asciiAddress; char_t *address; address = basicGetAddress(); asciiAddress = ballocUniToAsc(address, gstrlen(address)); sockaddr.sin_addr.s_addr = inet_addr(asciiAddress); bfree(B_L, asciiAddress); if (sockaddr.sin_addr.s_addr == INADDR_NONE) { errno = ENXIO; socketFree(sid); return -1; } } #endif /* (NO_GETHOSTBYNAME || VXWORKS) */ } } bcast = sp->flags & SOCKET_BROADCAST; if (bcast) { sp->flags |= SOCKET_DATAGRAM; } dgram = sp->flags & SOCKET_DATAGRAM; /* * Create the socket. Support for datagram sockets. Set the close on * exec flag so children don't inherit the socket. */ sp->sock = socket(AF_INET, dgram ? SOCK_DGRAM: SOCK_STREAM, 0); if (sp->sock < 0) { socketFree(sid); return -1; } #ifndef __NO_FCNTL fcntl(sp->sock, F_SETFD, FD_CLOEXEC); #endif socketHighestFd = max(socketHighestFd, sp->sock); /* * If broadcast, we need to turn on broadcast capability. */ if (bcast) { int broadcastFlag = 1; if (setsockopt(sp->sock, SOL_SOCKET, SO_BROADCAST, (char *) &broadcastFlag, sizeof(broadcastFlag)) < 0) { socketFree(sid); return -1; } } /* * Host is set if we are the client */ if (host) { /* * Connect to the remote server in blocking mode, then go into * non-blocking mode if desired. */ if (!dgram) { if (! (sp->flags & SOCKET_BLOCK)) { /* * sockGen.c is only used for Windows products when blocking * connects are expected. This applies to webserver connectws. * Therefore the asynchronous connect code here is not compiled. */ #if (defined (WIN) || defined (CE)) && (!defined (LITTLEFOOT) && !defined (WEBS)) int flag; sp->flags |= SOCKET_ASYNC; /* * Set to non-blocking for an async connect */ flag = 1; if (ioctlsocket(sp->sock, FIONBIO, &flag) == SOCKET_ERROR) { socketFree(sid); return -1; } #else socketSetBlock(sid, 1); #endif /* #if (WIN || CE) && !(LITTLEFOOT || WEBS) */ } if ((rc = connect(sp->sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr))) < 0 && (rc = tryAlternateConnect(sp->sock, (struct sockaddr *) &sockaddr)) < 0) { #if (defined (WIN) || defined (CE)) if (socketGetError() != EWOULDBLOCK) { socketFree(sid); return -1; } #else socketFree(sid); return -1; #endif /* WIN || CE */ } } } else { /* * Bind to the socket endpoint and the call listen() to start listening */ rc = 1; setsockopt(sp->sock, SOL_SOCKET, SO_REUSEADDR, (char *)&rc, sizeof(rc)); if (bind(sp->sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr)) < 0) { socketFree(sid); return -1; } if (! dgram) { if (listen(sp->sock, SOMAXCONN) < 0) { socketFree(sid); return -1; } sp->flags |= SOCKET_LISTENING; } sp->handlerMask |= SOCKET_READABLE; } /* * Set the blocking mode */ if (flags & SOCKET_BLOCK) { socketSetBlock(sid, 1); } else { socketSetBlock(sid, 0); } return sid; }
int jk_open_socket(struct sockaddr_in *addr, int ndelay, int keepalive, jk_logger_t *l) { int sock; jk_log(l, JK_LOG_DEBUG, "Into jk_open_socket\n"); sock = socket(AF_INET, SOCK_STREAM, 0); if(sock > -1) { int ret; /* Tries to connect to JServ (continues trying while error is EINTR) */ do { jk_log(l, JK_LOG_DEBUG, "jk_open_socket, try to connect socket = %d\n", sock); ret = connect(sock, (struct sockaddr *)addr, sizeof(struct sockaddr_in)); #if defined(WIN32) || (defined(NETWARE) && defined(__NOVELL_LIBC__)) if(SOCKET_ERROR == ret) { errno = WSAGetLastError() - WSABASEERR; } #endif /* WIN32 */ jk_log(l, JK_LOG_DEBUG, "jk_open_socket, after connect ret = %d\n", ret); } while (-1 == ret && EINTR == errno); /* Check if we connected */ if(0 == ret) { int keep = 1; if(ndelay) { int set = 1; jk_log(l, JK_LOG_DEBUG, "jk_open_socket, set TCP_NODELAY to on\n"); setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&set, sizeof(set)); } if (keepalive) { jk_log(l, JK_LOG_DEBUG, "jk_open_socket, set SO_KEEPALIVE to on\n"); setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&keep, sizeof(keep)); } jk_log(l, JK_LOG_DEBUG, "jk_open_socket, return, sd = %d\n", sock); return sock; } jk_log(l, JK_LOG_INFO, "jk_open_socket, connect() failed errno = %d\n", errno); jk_close_socket(sock); } else { #if defined(WIN32) || (defined(NETWARE) && defined(__NOVELL_LIBC__)) errno = WSAGetLastError() - WSABASEERR; #endif /* WIN32 */ jk_log(l, JK_LOG_ERROR, "jk_open_socket, socket() failed errno = %d\n", errno); } return -1; }
int OMXPlayerSync::setUpConnection () { int i; if ( syncType == SYNC_SERVER ) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == sockfd) { perror("0:socket"); return 1; } if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &forceRebind, sizeof(int))) { perror("0:setsockopt"); return 1; } memset((void *) &server, 0, sizeof(struct sockaddr_in)); server.sin_family = AF_INET; server.sin_port = htons( port ); server.sin_addr.s_addr = INADDR_ANY; if (-1 == bind(sockfd, (const struct sockaddr *) &server, sizeof(struct sockaddr_in))) { perror("0:bind"); return 1; } if (-1 == listen(sockfd, 0)) { perror("0:listen"); return 1; } // Set up the client sockets for ( i = 0; i < numNodes && i < MAX_NUM_CLIENT_SOCKETS; i++) { clientSocket [ i ] = accept(sockfd, (struct sockaddr *) &client, &clientaddrlen); if (-1 == clientSocket [ i ]) { perror("0:accept"); return 1; } } return 0; } else { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == sockfd) { perror("1:socket"); return 1; } if (0 != getaddrinfo(serverAddress.c_str (), NULL, NULL, &serverinfo)) { perror("getaddrinfo"); return 1; } /*Copy size of sockaddr_in b/c res->ai_addr to big for this example*/ memcpy(&server, serverinfo->ai_addr, sizeof(struct sockaddr_in)); server.sin_family = AF_INET; server.sin_port = htons( port ); freeaddrinfo(serverinfo); #ifdef LOOP_UNTIL_CONNECT while ( true ) { if (-1 != connect(sockfd, (const struct sockaddr *) &server, sizeof(struct sockaddr_in))) { break; } usleep ( CONNECT_SLEEP_PERIOD ); } #else if (-1 == connect(sockfd, (const struct sockaddr *) &server, sizeof(struct sockaddr_in))) { perror("1:connect"); return 1; } #endif // LOOP_UNTIL_CONNECT return 0; } }
void socket_server() { //The port you want the server to listen on int host_port= 1101; unsigned short wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )) { fprintf(stderr, "No sock dll %d\n",WSAGetLastError()); goto FINISH; } //Initialize sockets and set options int hsock; int * p_int ; hsock = socket(AF_INET, SOCK_STREAM, 0); if(hsock == -1){ printf("Error initializing socket %d\n",WSAGetLastError()); goto FINISH; } p_int = (int*)malloc(sizeof(int)); *p_int = 1; if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )|| (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){ printf("Error setting options %d\n", WSAGetLastError()); free(p_int); goto FINISH; } free(p_int); //Bind and listen struct sockaddr_in my_addr; my_addr.sin_family = AF_INET ; my_addr.sin_port = htons(host_port); memset(&(my_addr.sin_zero), 0, 8); my_addr.sin_addr.s_addr = INADDR_ANY ; /* if you get error in bind make sure nothing else is listening on that port */ if( bind( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){ fprintf(stderr,"Error binding to socket %d\n",WSAGetLastError()); goto FINISH; } if(listen( hsock, 10) == -1 ){ fprintf(stderr, "Error listening %d\n",WSAGetLastError()); goto FINISH; } //Now lets do the actual server stuff int* csock; sockaddr_in sadr; int addr_size = sizeof(SOCKADDR); while(true){ printf("waiting for a connection\n"); csock = (int*)malloc(sizeof(int)); if((*csock = accept( hsock, (SOCKADDR*)&sadr, &addr_size))!= INVALID_SOCKET ){ //printf("Received connection from %s",inet_ntoa(sadr.sin_addr)); CreateThread(0,0,&SocketHandler, (void*)csock , 0,0); } else{ fprintf(stderr, "Error accepting %d\n",WSAGetLastError()); } } FINISH: ; }
int main(){ OTRL_INIT; OtrlUserState userstate; char *newmessage = NULL; char *nlmsg=NULL; OtrlMessageAppOps ui_ops; int sockfd, clientfd, recvbytes, recv_ret; socklen_t sin_size; char buf[1024], pwdbuf[1024]; char *dbuf; struct sockaddr_in remote_addr, my_addr; fd_set fds; int one = 1; /* initialize ui callbacks */ memset(&ui_ops, 0, sizeof(OtrlMessageAppOps)); ui_ops.inject_message= inject_msg; ui_ops.gone_secure=gone_secure; printf("\033[31mStarting driver...\033[0m\n"); /* initialize socket connection */ sockfd = socket(AF_INET, SOCK_STREAM, 0); my_addr.sin_family=AF_INET; my_addr.sin_port= htons(3333); my_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(my_addr.sin_zero),8); /* Allow rebinding to address */ setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); exit(1); } if (listen(sockfd, 1) == -1) { perror("listen"); exit(1); } sin_size = sizeof(struct sockaddr_in); if ((clientfd = accept(sockfd, (struct sockaddr *)&remote_addr, \ &sin_size)) == -1) { perror("accept"); } printf("\033[31mConnected to Bob\033[0m\n"); /* create userstate, and read the private key */ userstate = otrl_userstate_create(); getcwd(pwdbuf, 1024); strcat(pwdbuf, "/private_key"); otrl_privkey_read(userstate, pwdbuf); /* Clients send messages asynchronously*/ while(1){ FD_ZERO(&fds); FD_SET(0, &fds); FD_SET(clientfd, &fds); select(clientfd+1, &fds, NULL, NULL, NULL); if(FD_ISSET(0, &fds)){ /* send message */ fgets(buf, 1023, stdin); buf[strlen(buf)-1]= '\0'; printf("\033[31mTo OTR:%d:\033[0m%s\n\033[0m",strlen(buf), buf); dbuf = strdup(buf); otrl_message_sending(userstate, &ui_ops, NULL, "*****@*****.**", "msn", "*****@*****.**", &dbuf, NULL, &newmessage, OTRL_FRAGMENT_SEND_SKIP, NULL, NULL, NULL, NULL); free(dbuf); nlmsg = (char*)malloc(strlen(newmessage)+2); memcpy(nlmsg, newmessage, strlen(newmessage)); nlmsg[strlen(newmessage)]='\n'; nlmsg[strlen(newmessage)+1]='\0'; send(clientfd, nlmsg, strlen(nlmsg), 0); printf("\033[31mTo network:%d:\033[35m%s\033[0m\n\033[0m", strlen(newmessage), newmessage); }else{ /*receive message */ recvbytes=recv(clientfd, buf, MAXDATASIZE, 0); if(recvbytes==0) break; recvbytes--; buf[recvbytes] = '\0'; if(buf[recvbytes-1]=='\r'){ recvbytes--; buf[recvbytes]='\0'; } printf("\033[31mFrom network:%d:\033[35m %s\033[0m\n",recvbytes, buf); recv_ret=otrl_message_receiving(userstate, &ui_ops, &clientfd, "*****@*****.**", "msn", "*****@*****.**", buf, &newmessage, NULL, NULL, NULL, NULL, NULL); if(recv_ret==0) printf("\033[31mFrom OTR:%d:\033[0m %s\n", newmessage ? strlen(newmessage) : 0, newmessage); } } return 0; }
REDIS credis_connect(const char *host, int port, int timeout) { int fd, rc,flags ,yes = 1, use_he = 0; struct sockaddr_in sa; struct hostent *he; REDIS rhnd; #ifdef WIN32 unsigned long addr; WSADATA data; if (WSAStartup(MAKEWORD(2,2), &data) != 0) { DEBUG("Failed to init Windows Sockets DLL\n"); return NULL; } #endif if ((rhnd = cr_new()) == NULL) return NULL; if (host == NULL) host = "127.0.0.1"; if (port == 0) port = 6379; #ifdef WIN32 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 || setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&yes, sizeof(yes)) == -1 || setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes)) == -1) goto error; #else if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 || setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&yes, sizeof(yes)) == -1 || setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&yes, sizeof(yes)) == -1) goto error; #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); #ifdef WIN32 /* TODO use getaddrinfo() instead! */ addr = inet_addr(host); if (addr == INADDR_NONE) { he = gethostbyname(host); use_he = 1; } else { he = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); use_he = 1; } #else if (inet_aton(host, &sa.sin_addr) == 0) { he = gethostbyname(host); use_he = 1; } #endif if (use_he) { if (he == NULL) goto error; memcpy(&sa.sin_addr, he->h_addr, sizeof(struct in_addr)); } /* connect with user specified timeout */ #ifndef WIN32 flags = fcntl(fd, F_GETFL); if ((rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) < 0) { DEBUG("Setting socket non-blocking failed with: %d\n", rc); } #endif if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0) { #ifndef WIN32 if (errno != EINPROGRESS) goto error; #endif if (cr_selectwritable(fd, timeout) > 0) { int err; socklen_t len = sizeof(err); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&err, &len) == -1 || err) goto error; } else /* timeout or select error */ goto error; } /* else connect completed immediately */ strcpy(rhnd->ip, inet_ntoa(sa.sin_addr)); rhnd->port = port; rhnd->fd = fd; rhnd->timeout = timeout; /* We can receive 2 version formats: x.yz and x.y.z, where x.yz was only used prior * first 1.1.0 release(?), e.g. stable releases 1.02 and 1.2.6 */ if (cr_sendfandreceive(rhnd, CR_BULK, "INFO\r\n") == 0) { int items = sscanf(rhnd->reply.bulk, "redis_version:%d.%d.%d\r\n", &(rhnd->version.major), &(rhnd->version.minor), &(rhnd->version.patch)); if(items == 0) items = sscanf(rhnd->reply.bulk, "# Server\r\nredis_version:%d.%d.%d\r\n", &(rhnd->version.major), &(rhnd->version.minor), &(rhnd->version.patch)); if (items < 2) goto error; if (items == 2) { rhnd->version.patch = rhnd->version.minor; rhnd->version.minor = 0; } DEBUG("Connected to Redis version: %d.%d.%d\n", rhnd->version.major, rhnd->version.minor, rhnd->version.patch); } return rhnd; error: if (fd > 0) close(fd); cr_delete(rhnd); return NULL; }
static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret=1; int *ip; struct sockaddr *to = NULL; bio_dgram_data *data = NULL; #if defined(IP_MTU_DISCOVER) || defined(IP_MTU) long sockopt_val = 0; unsigned int sockopt_len = 0; #endif #ifdef OPENSSL_SYS_LINUX socklen_t addr_len; union { struct sockaddr sa; struct sockaddr_in s4; #if OPENSSL_USE_IPV6 struct sockaddr_in6 s6; #endif } addr; #endif data = (bio_dgram_data *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: num=0; case BIO_C_FILE_SEEK: ret=0; break; case BIO_C_FILE_TELL: case BIO_CTRL_INFO: ret=0; break; case BIO_C_SET_FD: dgram_clear(b); b->num= *((int *)ptr); b->shutdown=(int)num; b->init=1; break; case BIO_C_GET_FD: if (b->init) { ip=(int *)ptr; if (ip != NULL) *ip=b->num; ret=b->num; } else ret= -1; break; case BIO_CTRL_GET_CLOSE: ret=b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown=(int)num; break; case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: ret=0; break; case BIO_CTRL_DUP: case BIO_CTRL_FLUSH: ret=1; break; case BIO_CTRL_DGRAM_CONNECT: to = (struct sockaddr *)ptr; #if 0 if (connect(b->num, to, sizeof(struct sockaddr)) < 0) { perror("connect"); ret = 0; } else { #endif switch (to->sa_family) { case AF_INET: memcpy(&data->peer,to,sizeof(data->peer.sa_in)); break; #if OPENSSL_USE_IPV6 case AF_INET6: memcpy(&data->peer,to,sizeof(data->peer.sa_in6)); break; #endif default: memcpy(&data->peer,to,sizeof(data->peer.sa)); break; } #if 0 } #endif break; /* (Linux)kernel sets DF bit on outgoing IP packets */ case BIO_CTRL_DGRAM_MTU_DISCOVER: #ifdef OPENSSL_SYS_LINUX addr_len = (socklen_t)sizeof(addr); memset((void *)&addr, 0, sizeof(addr)); if (getsockname(b->num, &addr.sa, &addr_len) < 0) { ret = 0; break; } sockopt_len = sizeof(sockopt_val); switch (addr.sa.sa_family) { case AF_INET: sockopt_val = IP_PMTUDISC_DO; if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER, &sockopt_val, sizeof(sockopt_val))) < 0) perror("setsockopt"); break; #if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER) case AF_INET6: sockopt_val = IPV6_PMTUDISC_DO; if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &sockopt_val, sizeof(sockopt_val))) < 0) perror("setsockopt"); break; #endif default: ret = -1; break; } ret = -1; #else break; #endif case BIO_CTRL_DGRAM_QUERY_MTU: #ifdef OPENSSL_SYS_LINUX addr_len = (socklen_t)sizeof(addr); memset((void *)&addr, 0, sizeof(addr)); if (getsockname(b->num, &addr.sa, &addr_len) < 0) { ret = 0; break; } sockopt_len = sizeof(sockopt_val); switch (addr.sa.sa_family) { case AF_INET: if ((ret = getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val, &sockopt_len)) < 0 || sockopt_val < 0) { ret = 0; } else { /* we assume that the transport protocol is UDP and no * IP options are used. */ data->mtu = sockopt_val - 8 - 20; ret = data->mtu; } break; #if OPENSSL_USE_IPV6 && defined(IPV6_MTU) case AF_INET6: if ((ret = getsockopt(b->num, IPPROTO_IPV6, IPV6_MTU, (void *)&sockopt_val, &sockopt_len)) < 0 || sockopt_val < 0) { ret = 0; } else { /* we assume that the transport protocol is UDP and no * IPV6 options are used. */ data->mtu = sockopt_val - 8 - 40; ret = data->mtu; } break; #endif default: ret = 0; break; } #else ret = 0; #endif break; case BIO_CTRL_DGRAM_GET_MTU: return data->mtu; break; case BIO_CTRL_DGRAM_SET_MTU: data->mtu = num; ret = num; break; case BIO_CTRL_DGRAM_SET_CONNECTED: to = (struct sockaddr *)ptr; if ( to != NULL) { data->connected = 1; switch (to->sa_family) { case AF_INET: memcpy(&data->peer,to,sizeof(data->peer.sa_in)); break; #if OPENSSL_USE_IPV6 case AF_INET6: memcpy(&data->peer,to,sizeof(data->peer.sa_in6)); break; #endif default: memcpy(&data->peer,to,sizeof(data->peer.sa)); break; } } else { data->connected = 0; memset(&(data->peer), 0x00, sizeof(data->peer)); } break; case BIO_CTRL_DGRAM_GET_PEER: switch (data->peer.sa.sa_family) { case AF_INET: ret=sizeof(data->peer.sa_in); break; #if OPENSSL_USE_IPV6 case AF_INET6: ret=sizeof(data->peer.sa_in6); break; #endif default: ret=sizeof(data->peer.sa); break; } if (num==0 || num>ret) num=ret; memcpy(ptr,&data->peer,(ret=num)); break; case BIO_CTRL_DGRAM_SET_PEER: to = (struct sockaddr *) ptr; switch (to->sa_family) { case AF_INET: memcpy(&data->peer,to,sizeof(data->peer.sa_in)); break; #if OPENSSL_USE_IPV6 case AF_INET6: memcpy(&data->peer,to,sizeof(data->peer.sa_in6)); break; #endif default: memcpy(&data->peer,to,sizeof(data->peer.sa)); break; } break; case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT: memcpy(&(data->next_timeout), ptr, sizeof(struct timeval)); break; #if defined(SO_RCVTIMEO) case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT: #ifdef OPENSSL_SYS_WINDOWS { struct timeval *tv = (struct timeval *)ptr; int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000; if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, sizeof(timeout)) < 0) { perror("setsockopt"); ret = -1; } } #else if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr, sizeof(struct timeval)) < 0) { perror("setsockopt"); ret = -1; } #endif break; case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT: #ifdef OPENSSL_SYS_WINDOWS { int timeout, sz = sizeof(timeout); struct timeval *tv = (struct timeval *)ptr; if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, &sz) < 0) { perror("getsockopt"); ret = -1; } else { tv->tv_sec = timeout / 1000; tv->tv_usec = (timeout % 1000) * 1000; ret = sizeof(*tv); } } #else if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr, (void *)&ret) < 0) { perror("getsockopt"); ret = -1; } #endif break; #endif #if defined(SO_SNDTIMEO) case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT: #ifdef OPENSSL_SYS_WINDOWS { struct timeval *tv = (struct timeval *)ptr; int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000; if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, (void*)&timeout, sizeof(timeout)) < 0) { perror("setsockopt"); ret = -1; } } #else if ( setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr, sizeof(struct timeval)) < 0) { perror("setsockopt"); ret = -1; } #endif break; case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT: #ifdef OPENSSL_SYS_WINDOWS { int timeout, sz = sizeof(timeout); struct timeval *tv = (struct timeval *)ptr; if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, (void*)&timeout, &sz) < 0) { perror("getsockopt"); ret = -1; } else { tv->tv_sec = timeout / 1000; tv->tv_usec = (timeout % 1000) * 1000; ret = sizeof(*tv); } } #else if ( getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr, (void *)&ret) < 0) { perror("getsockopt"); ret = -1; } #endif break; #endif case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP: /* fall-through */ case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP: #ifdef OPENSSL_SYS_WINDOWS if ( data->_errno == WSAETIMEDOUT) #else if ( data->_errno == EAGAIN) #endif { ret = 1; data->_errno = 0; } else ret = 0; break; #ifdef EMSGSIZE case BIO_CTRL_DGRAM_MTU_EXCEEDED: if ( data->_errno == EMSGSIZE) { ret = 1; data->_errno = 0; } else ret = 0; break; #endif default: ret=0; break; } return(ret); }
static void dgram_adjust_rcv_timeout(BIO *b) { #if defined(SO_RCVTIMEO) bio_dgram_data *data = (bio_dgram_data *)b->ptr; int sz = sizeof(int); /* Is a timer active? */ if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0) { struct timeval timenow, timeleft; /* Read current socket timeout */ #ifdef OPENSSL_SYS_WINDOWS int timeout; if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, &sz) < 0) { perror("getsockopt"); } else { data->socket_timeout.tv_sec = timeout / 1000; data->socket_timeout.tv_usec = (timeout % 1000) * 1000; } #else if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &(data->socket_timeout), (void *)&sz) < 0) { perror("getsockopt"); } #endif /* Get current time */ get_current_time(&timenow); /* Calculate time left until timer expires */ memcpy(&timeleft, &(data->next_timeout), sizeof(struct timeval)); timeleft.tv_sec -= timenow.tv_sec; timeleft.tv_usec -= timenow.tv_usec; if (timeleft.tv_usec < 0) { timeleft.tv_sec--; timeleft.tv_usec += 1000000; } if (timeleft.tv_sec < 0) { timeleft.tv_sec = 0; timeleft.tv_usec = 1; } /* Adjust socket timeout if next handhake message timer * will expire earlier. */ if ((data->socket_timeout.tv_sec == 0 && data->socket_timeout.tv_usec == 0) || (data->socket_timeout.tv_sec > timeleft.tv_sec) || (data->socket_timeout.tv_sec == timeleft.tv_sec && data->socket_timeout.tv_usec >= timeleft.tv_usec)) { #ifdef OPENSSL_SYS_WINDOWS timeout = timeleft.tv_sec * 1000 + timeleft.tv_usec / 1000; if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, (void*)&timeout, sizeof(timeout)) < 0) { perror("setsockopt"); } #else if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &timeleft, sizeof(struct timeval)) < 0) { perror("setsockopt"); } #endif } } #endif }
BOOL CTroubleShootDlg::ChangeNetDeviceIP(CString strIP){ BOOL ret=FALSE; CString strlog; int nRet = 0; short nmsgType=UPD_BROADCAST_QRY_MSG; const DWORD END_FLAG = 0x00000000; TIMEVAL time; time.tv_sec =3; time.tv_usec = 1000; fd_set fdSocket; BYTE buffer[512] = {0}; BYTE pSendBuf[1024]; ZeroMemory(pSendBuf, 255); pSendBuf[0] = 0x66; memcpy(pSendBuf + 1, (BYTE*)&END_FLAG, 4); int nSendLen = 17; int time_out=0; USES_CONVERSION; CString stroldipaddress,strnewipadress,strlocalipaddress,strnewsubnet,strnewgateway; stroldipaddress=strIP; SOCKET sListen=NULL; // for (int i=0;i<allsubnets.size();i++) // { m_edit_newip.GetWindowTextW(strnewipadress); for (int i = 0;i<g_Vector_Subnet.size ();i++) { if (CheckTheSameSubnet(g_Vector_Subnet.at(i).StrIP,strnewipadress)) { strnewgateway = g_Vector_Subnet.at(i).StrGetway; strnewsubnet = g_Vector_Subnet.at(i).StrMask; break; } } //GetNewIP(strnewipadress,allsubnets[i].StrIP); if (strnewipadress.Find(_T("0.0.0"))!=-1)//对0.0.0.0的过滤掉 { return FALSE; } #pragma region new_socket SOCKET h_scan_Broad=NULL; SOCKADDR_IN h_scan_bcast; SOCKADDR_IN h_scan_siBind; h_scan_Broad=::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); BOOL bBroadcast=TRUE; ::setsockopt(h_scan_Broad,SOL_SOCKET,SO_BROADCAST,(char*)&bBroadcast,sizeof(BOOL)); int iMode=1; ioctlsocket(h_scan_Broad,FIONBIO, (u_long FAR*) &iMode); BOOL bDontLinger = FALSE; setsockopt( h_scan_Broad, SOL_SOCKET, SO_DONTLINGER, ( const char* )&bDontLinger, sizeof( BOOL ) ); //SOCKADDR_IN bcast; h_scan_bcast.sin_family=AF_INET; //bcast.sin_addr.s_addr=nBroadCastIP; h_scan_bcast.sin_addr.s_addr=INADDR_BROADCAST; h_scan_bcast.sin_port=htons(UDP_BROADCAST_PORT); h_scan_siBind.sin_family=AF_INET; h_scan_siBind.sin_addr.s_addr = INADDR_ANY; #pragma endregion new_socket local_enthernet_ip=m_net_product_node.NetworkCard_Address; WideCharToMultiByte( CP_ACP, 0, local_enthernet_ip.GetBuffer(), -1, local_network_ip, 255, NULL, NULL ); h_siBind.sin_family=AF_INET; h_siBind.sin_addr.s_addr = inet_addr(local_network_ip); if( -1 == bind(h_scan_Broad,(SOCKADDR*)&h_siBind,sizeof(h_siBind)))//把网卡地址强行绑定到Socket { //MessageBox(_T("Network Initial Fail")); ret= FALSE; } LPCSTR szIP = W2A(stroldipaddress); DWORD dwIP = inet_addr(szIP); IN_ADDR ia; ia.S_un.S_addr = dwIP; //////////////////Old IP//////////////////////////////////// pSendBuf[1]=ia.S_un.S_un_b.s_b1; pSendBuf[2]=ia.S_un.S_un_b.s_b2; pSendBuf[3]=ia.S_un.S_un_b.s_b3; pSendBuf[4]=ia.S_un.S_un_b.s_b4; ///////////////////New IP/////////////////////////////////////////// szIP = W2A(strnewipadress); dwIP = inet_addr(szIP); ia.S_un.S_addr = dwIP; /////////////////////////////////////////////////////////// pSendBuf[5]=ia.S_un.S_un_b.s_b1; pSendBuf[6]=ia.S_un.S_un_b.s_b2; pSendBuf[7]=ia.S_un.S_un_b.s_b3; pSendBuf[8]=ia.S_un.S_un_b.s_b4; //////////////////////////////////////////////////////////////////// szIP = W2A(strnewsubnet); dwIP = inet_addr(szIP); ia.S_un.S_addr = dwIP; pSendBuf[9]=ia.S_un.S_un_b.s_b1; pSendBuf[10]=ia.S_un.S_un_b.s_b2; pSendBuf[11]=ia.S_un.S_un_b.s_b3; pSendBuf[12]=ia.S_un.S_un_b.s_b4; //////////////////////////////////////////////////////////////////// szIP = W2A(strnewgateway); dwIP = inet_addr(szIP); ia.S_un.S_addr = dwIP; pSendBuf[13]=ia.S_un.S_un_b.s_b1; pSendBuf[14]=ia.S_un.S_un_b.s_b2; pSendBuf[15]=ia.S_un.S_un_b.s_b3; pSendBuf[16]=ia.S_un.S_un_b.s_b4; FD_ZERO(&fdSocket); FD_SET(h_scan_Broad, &fdSocket); // fd_set fdSocket; // FD_ZERO(&fdSocket); // FD_SET(h_scan_Broad, &fdSocket); nRet = ::sendto(h_scan_Broad,(char*)pSendBuf,nSendLen,0,(sockaddr*)&h_bcast,sizeof(h_bcast)); if (nRet == SOCKET_ERROR) { int nError = WSAGetLastError(); ret= FALSE ; goto END_CHANGEIP_SCAN; } int nLen = sizeof(h_siBind); //while(pScanner->IsComScanRunning()) // Sleep(3000); fd_set fdRead = fdSocket; int nSelRet = ::select(0, &fdRead, NULL, NULL, &time); if (nSelRet == SOCKET_ERROR) { int nError = WSAGetLastError(); ret= FALSE ; goto END_CHANGEIP_SCAN; } if(nSelRet > 0) { ZeroMemory(buffer, 512); //Sleep(3000); do { int nRet = ::recvfrom(h_scan_Broad,(char*)buffer, 512, 0, (sockaddr*)&h_siBind, &nLen); // int nRet = ::recvfrom(hBroad,(char*)&buffer[0], nsize, 0, (sockaddr*)&addrRemote, &nLen); BYTE szIPAddr[4] = {0}; if(nRet > 0) { FD_ZERO(&fdSocket); if(buffer[0]==0x67)//收到正确的回复了 { SaveNewIPAddress(strnewipadress,stroldipaddress); ret=TRUE; MessageBox(_T("Successfull")); CString strSql; CppSQLite3DB SqliteDBBuilding; CppSQLite3Table table; CppSQLite3Query q; SqliteDBBuilding.open((UTF8MBSTR)g_strCurBuildingDatabasefilePath); CString temp_serial_cs; temp_serial_cs.Format(_T("%u"),g_selected_serialnumber); strSql.Format(_T("select * from ALL_NODE where Serial_ID = '%s' "),temp_serial_cs); //m_pRs->Open((_variant_t)strSql,_variant_t((IDispatch *)m_pCon,true),adOpenStatic,adLockOptimistic,adCmdText); q = SqliteDBBuilding.execQuery((UTF8MBSTR)strSql); while(!q.eof()) { strSql.Format(_T("update ALL_NODE set Bautrate='%s' where Serial_ID= '%s'"),strnewipadress,temp_serial_cs); SqliteDBBuilding.execDML((UTF8MBSTR)strSql); q.nextRow(); } CMainFrame* pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); ::PostMessage(pFrame->m_hWnd, WM_MYMSG_REFRESHBUILDING,0,0); //Sleep(8000); // SetCommunicationType(1); // if (!Open_Socket2(strnewipadress,_wtoi(m_net_product_node.BuildingInfo.strIpPort))) // { // stroldipaddress=strnewipadress; // MessageBox(_T("Fail!")); // ret= FALSE; // } // else // { // close_com(); // } //m_flexGrid.put_TextMatrix(row_flags,NEW_IPADRESS,strnewipadress); //AfxMessageBox(_T("Change the ip successfully!")); //ret=TRUE; //return TRUE; break; } SHOW_TX_RX_TS FD_ZERO(&fdSocket); FD_SET(h_scan_Broad, &fdSocket); nLen = sizeof(h_scan_siBind); fdRead = fdSocket; nSelRet = ::select(0, &fdRead, NULL, NULL, &time); } } while (nSelRet>0); } else { MessageBox(_T("Fail!")); ret=FALSE; } END_CHANGEIP_SCAN: closesocket(h_scan_Broad); h_scan_Broad=NULL; //{ // //SOCKET soAck =::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // h_scan_Broad=::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // BOOL bBroadcast=TRUE; // ::setsockopt(h_scan_Broad,SOL_SOCKET,SO_BROADCAST,(char*)&bBroadcast,sizeof(BOOL)); // int iMode=1; // ioctlsocket(h_scan_Broad,FIONBIO, (u_long FAR*) &iMode); // BOOL bDontLinger = FALSE; // setsockopt( h_scan_Broad, SOL_SOCKET, SO_DONTLINGER, ( const char* )&bDontLinger, sizeof( BOOL ) ); // //SOCKADDR_IN bcast; // h_bcast.sin_family=AF_INET; // //bcast.sin_addr.s_addr=nBroadCastIP; // h_bcast.sin_addr.s_addr=INADDR_BROADCAST; // h_bcast.sin_port=htons(UDP_BROADCAST_PORT); // //SOCKADDR_IN siBind; // h_siBind.sin_family=AF_INET; // h_siBind.sin_addr.s_addr=INADDR_ANY; // h_siBind.sin_port=htons(RECV_RESPONSE_PORT); // ::bind(h_scan_Broad, (sockaddr*)&h_siBind,sizeof(h_siBind)); //} return ret; }
int main(int ac, char **av) { ssize_t l; char buf[2000]; int r; int n; /* Socket variables */ int s, exp; u_int yes=1; int port; struct sockaddr_in me, them; socklen_t sl = sizeof(struct sockaddr_in); struct pollfd fds[2]; /*Initialization*/{ port=3811; bzero(&me,sizeof(me)); me.sin_family= AF_INET; me.sin_port=htons(port); s=socket(AF_INET,SOCK_DGRAM,0); bind(s,(struct sockaddr *)&me,sizeof(me)); exp=socket(AF_INET,SOCK_STREAM,0); setsockopt(exp,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)); bind(exp,(struct sockaddr *)&me,sizeof(me)); listen(exp,10); bzero(&fds,sizeof(fds)); fcntl(s,F_SETFL,O_NONBLOCK); fcntl(exp,F_SETFL,O_NONBLOCK); fds[0].fd = s; fds[0].events |= POLLIN; fds[1].fd = exp, fds[1].events |= POLLIN; db_create(&db,NULL,0); db->set_cachesize(db, 0, 512*1024*1024, 0); db->open(db,NULL,"stats.db",NULL,DB_BTREE,DB_CREATE|DB_TRUNCATE,0); signal(SIGHUP,hup); signal(SIGINT,die); signal(SIGTERM,die); signal(SIGCHLD,child); signal(SIGUSR1,truncatedb); daemon(1,0); } /* Loop! loop! loop! */ for(;;) { n=0; r=poll(fds,2,-1); /* Process incoming UDP queue */ while(( fds[0].revents & POLLIN ) && ((l=recvfrom(s,&buf,1500,0,NULL,NULL))!=-1)) { if (l==EAGAIN) break; handleMessage((char *)&buf,l); n++; /* Still handle export connections under high load */ if (n==5000) break; } /* Process incoming TCP queue */ while((fds[1].revents & POLLIN ) && ((r=accept(exp,(struct sockaddr *)&them,&sl))!=-1)) { if (r==EWOULDBLOCK) break; handleConnection(r); } } return(0); }
int sio_open(int &argc, char ** &argv, const char*g_appname, const char*ver, const char*client) { char * port_str = getenv("SODACTRL_PORT"); if (port_str) { // connect socket int port = atoi(port_str); if (port <= 0) { fprintf(stderr, "Invalid port number (SODACTRL_PORT): %s\n", port_str); return -1; }; int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("Cannot create socket"); return -1; }; struct linger ling; ling.l_onoff = 1; ling.l_linger = 10; // try to send data for up to 10 seconds... if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) < 0) { perror("setsockopt(linger) failed"); }; struct sockaddr_in servaddr; struct hostent *host; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); const char * ip = getenv("SODACTRL_IP"); if (!ip) ip = "127.0.0.1"; servaddr.sin_addr.s_addr =inet_addr(ip); if (connect(fd, (sockaddr*)&servaddr, sizeof(servaddr)) < 0){ char bf[512]; snprintf(bf, sizeof(bf), "Cannot connect to %s:%d", ip, port); perror(bf); return -1; } ser_fd_read = ser_fd_write = fd; } else { // use STDIN/STDOUT ser_fd_read = 0; ser_fd_write = 1; }; fcntl(ser_fd_read, F_SETFL, O_NONBLOCK); fcntl(ser_fd_write, F_SETFL, O_NONBLOCK); char * dbgc = getenv("SERVIO_DEBUG"); sio_dbglevel = dbgc ? atoi(dbgc) : 50; char * commd = getenv("SERVIO_COMMDUMP"); sio_commdump = commd ? atoi(commd) : 0; const char* proto = "106"; if (g_appname[0] == '+') { proto = "101"; g_appname++; }; appname = strdup(g_appname); if (sio_write(SIO_DATA, "SYS-INIT\t%s\t%s\t%s\t%d\t%s", proto, appname, ver, getpid(), (client?client:"")) == -1) { perror("Cannot write to server"); return -1; }; noserv_mode = 0; // no need for 'SYS_WELCOME' when debug env is set - thus can run from console easliy if (isatty(ser_fd_read) && (ser_fd_read != ser_fd_write)) { noserv_mode = 1; printf("Using NO-SERVER mode - taking data, commands from tty, disabling GET\n"); return 0; }; // the only possible response to SYS-INIT with version 101 is SYS-WELCOME // wait 10 seconds for it... std::string resp; if (sio_read(resp, 10*1000) <= 0) { fprintf(stderr, "Server initial response timed out\n"); return -1; // no reponse }; if (resp.substr(0, 12)!="SYS-WELCOME\t") { for (int i=0; i<resp.length(); i++) if (resp[i]<32) resp[i]='#'; fprintf(stderr, "Server initial response is junk: %s\n", resp.c_str()); return -1; }; return 0; };
int main(int argc, char *argv[]) { int connSock; int in; int i; int ret; int flags; struct sockaddr_in servaddr; struct sctp_status status; struct sctp_sndrcvinfo sndrcvinfo; struct sctp_event_subscribe events; struct sctp_initmsg initmsg; char buffer[MAX_BUFFER + 1]; char inBuffer[MAX_BUFFER + 1]; /* Create an SCTP TCP-Style Socket */ connSock = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP); /* Specify that a maximum of 5 streams will be available per socket */ memset(&initmsg, 0, sizeof(initmsg)); initmsg.sinit_num_ostreams = 5; initmsg.sinit_max_instreams = 5; initmsg.sinit_max_attempts = 4; ret = setsockopt(connSock, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(initmsg)); /* Specify the peer endpoint to which we'll connect */ bzero((void *) &servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(MY_PORT_NUM); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* Connect to the server */ ret = connect(connSock, (struct sockaddr *) &servaddr, sizeof(servaddr)); /* Enable receipt of SCTP Snd/Rcv Data via sctp_recvmsg */ memset((void *) &events, 0, sizeof(events)); events.sctp_data_io_event = 1; ret = setsockopt(connSock, SOL_SCTP, SCTP_EVENTS, (const void *) &events, sizeof(events)); /* Read and emit the status of the Socket (optional step) */ in = sizeof(status); ret = getsockopt(connSock, SOL_SCTP, SCTP_STATUS, (void *) &status, (socklen_t *) &in); printf("assoc id = %d\n", status.sstat_assoc_id); printf("state = %d\n", status.sstat_state); printf("instrms = %d\n", status.sstat_instrms); printf("outstrms = %d\n", status.sstat_outstrms); /* Expect two messages from the peer */ for (i = 0 ; i < 2 ; i++) { in = sctp_recvmsg(connSock, (void *) buffer, sizeof(buffer), (struct sockaddr *) NULL, 0, &sndrcvinfo, &flags); if (in > 0) { //buffer[in] = 0; strncpy(inBuffer, buffer, in); if (sndrcvinfo.sinfo_stream == LOCALTIME_STREAM) { printf("(Local) %s", buffer); } else if (sndrcvinfo.sinfo_stream == GMT_STREAM) { printf("(GMT) %s", buffer); } } } /* Close our socket and exit */ close(connSock); return 0; }
/* returns a bound socket matching a connection request * * sets verdict on request packet if ipq or nfq was used and the port is already bound * * in the latter case, -1 is returned */ int get_boundsock(struct sockaddr_in *server_addr, uint16_t port, int type) { int fd, sockopt; #ifdef USE_IPQ_MON int status; #endif if ((type != SOCK_DGRAM) && (type != SOCK_STREAM)) { logmsg(LOG_ERR, 1, "Error - Socket type %d not supported.\n", type); exit(EXIT_FAILURE); } if (!(fd = socket(AF_INET, type, 0))) { logmsg(LOG_ERR, 1, "Error - Could not create socket: %m.\n"); exit(EXIT_FAILURE); } sockopt = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) < 0) logmsg(LOG_WARN, 1, "Warning - Unable to set SO_REUSEADDR for server socket.\n"); bzero((char *) server_addr, sizeof(struct sockaddr_in)); server_addr->sin_family = AF_INET; server_addr->sin_addr.s_addr = bind_address.s_addr; server_addr->sin_port = port; if ((bind(fd, (struct sockaddr *) server_addr, sizeof(struct sockaddr_in))) != 0) { /* we already got one server process */ logmsg(LOG_DEBUG, 1, "Unable to bind to port %u/tcp: %m.\n", ntohs(port)); #ifdef USE_IPQ_MON /* hand packet processing back to the kernel */ if ((status = ipq_set_verdict(h, packet->packet_id, NF_ACCEPT, 0, NULL)) < 0) { logmsg(LOG_ERR, 1, "Error - Could not set verdict on packet: %s.\n", ipq_errstr()); ipq_destroy_handle(h); exit(EXIT_FAILURE); } logmsg(LOG_DEBUG, 1, "IPQ - Successfully set verdict on packet.\n"); return(-1); #else #ifdef USE_NFQ_MON /* hand packet processing back to the kernel */ /* nfq_set_verdict()'s return value is undocumented, * but digging the source of libnetfilter_queue and libnfnetlink reveals * that it's just the passed-through value of a sendmsg() */ if (nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL) == -1) { logmsg(LOG_ERR, 1, "Error - Could not set verdict on packet.\n"); nfq_destroy_queue(qh); exit(EXIT_FAILURE); } logmsg(LOG_DEBUG, 1, "NFQ - Successfully set verdict on packet.\n"); /* a dynamic server is already present */ close(fd); return(-1); #else /* if bind() did not fail for 'port already in use' but for some other reason, * we're in troubles and want a verbose error message */ if (errno != 98) logmsg(LOG_NOISY, 1, "Warning - Could not bind to port %u/tcp: %m.\n", ntohs(port)); exit(EXIT_FAILURE); #endif #endif } logmsg(LOG_DEBUG, 1, "Socket created, file descriptor is %d.\n", fd); return(fd); }
int swPort_set_option(swListenPort *ls) { int sock = ls->sock; //reuse address int option = 1; //reuse port #ifdef HAVE_REUSEPORT if (SwooleG.reuse_port) { if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &option, sizeof(int)) < 0) { swSysError("setsockopt(SO_REUSEPORT) failed."); SwooleG.reuse_port = 0; } } #endif if (swSocket_is_dgram(ls->type)) { int bufsize = SwooleG.socket_buffer_size; setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)); setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)); return SW_OK; } #ifdef SW_USE_OPENSSL if (ls->open_ssl_encrypt) { if (ls->ssl_cert_file == NULL || ls->ssl_key_file == NULL) { swWarn("SSL error, require ssl_cert_file and ssl_key_file."); return SW_ERR; } ls->ssl_context = swSSL_get_context(ls->ssl_method, ls->ssl_cert_file, ls->ssl_key_file); if (ls->ssl_context == NULL) { swWarn("swSSL_get_context() error."); return SW_ERR; } if (ls->ssl_client_cert_file && swSSL_set_client_certificate(ls->ssl_context, ls->ssl_client_cert_file, ls->ssl_verify_depth) == SW_ERR) { swWarn("swSSL_set_client_certificate() error."); return SW_ERR; } if (ls->open_http_protocol) { ls->ssl_config.http = 1; } if (ls->open_http2_protocol) { ls->ssl_config.http_v2 = 1; swSSL_server_http_advise(ls->ssl_context, &ls->ssl_config); } if (swSSL_server_set_cipher(ls->ssl_context, &ls->ssl_config) < 0) { swWarn("swSSL_server_set_cipher() error."); return SW_ERR; } } if (ls->ssl) { if (!ls->ssl_cert_file) { swWarn("need to set [ssl_cert_file] option."); return SW_ERR; } if (!ls->ssl_key_file) { swWarn("need to set [ssl_key_file] option."); return SW_ERR; } } #endif //listen stream socket if (listen(sock, ls->backlog) < 0) { swWarn("listen(%s:%d, %d) failed. Error: %s[%d]", ls->host, ls->port, ls->backlog, strerror(errno), errno); return SW_ERR; } #ifdef TCP_DEFER_ACCEPT if (ls->tcp_defer_accept) { if (setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, (const void*) &ls->tcp_defer_accept, sizeof(int)) < 0) { swSysError("setsockopt(TCP_DEFER_ACCEPT) failed."); } } #endif #ifdef TCP_FASTOPEN if (ls->tcp_fastopen) { if (setsockopt(sock, IPPROTO_TCP, TCP_FASTOPEN, (const void*) &ls->tcp_fastopen, sizeof(int)) < 0) { swSysError("setsockopt(TCP_FASTOPEN) failed."); } } #endif #ifdef SO_KEEPALIVE if (ls->open_tcp_keepalive == 1) { option = 1; if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &option, sizeof(option)) < 0) { swSysError("setsockopt(SO_KEEPALIVE) failed."); } #ifdef TCP_KEEPIDLE setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, (void*) &ls->tcp_keepidle, sizeof(int)); setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, (void *) &ls->tcp_keepinterval, sizeof(int)); setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, (void *) &ls->tcp_keepcount, sizeof(int)); #endif } #endif return SW_OK; }
int mcast_join_group( int sock, IP *addr, const char ifce[] ) { #if defined(MCAST_JOIN_GROUP) && !defined(__APPLE__) struct group_req req; if( ifce ) { if( (req.gr_interface = if_nametoindex( ifce )) == 0 ) { log_err( "LPD: Cannot find interface '%s' for multicast: %s", ifce, strerror( errno ) ); return -1; } } else { req.gr_interface = 0; } memcpy( &req.gr_group, addr, addr_len( addr ) ); if( setsockopt( sock, IPPROTO_IP, MCAST_JOIN_GROUP, &req, sizeof(req) ) < 0 ) { log_warn( "LPD: Failed to join multicast group: %s", strerror( errno ) ); return -1; } return 0; #else switch( addr->ss_family ) { case AF_INET: { struct ip_mreq mreq; struct ifreq ifreq; memcpy( &mreq.imr_multiaddr, &((IP4*) addr)->sin_addr, 4 ); if( ifce ) { strncpy( ifreq.ifr_name, ifce, IFNAMSIZ ); if( ioctl( sock, SIOCGIFADDR, &ifreq ) < 0 ) { log_err( "LPD: Cannot find interface '%s' for multicast: %s", ifce, strerror( errno ) ); return -1; } memcpy( &mreq.imr_interface, &((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr, 4); } else { mreq.imr_interface.s_addr = htonl( INADDR_ANY ); } if( setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0 ) { log_warn( "LPD: Failed to join IPv4 multicast group: %s", strerror( errno ) ); return -1; } return 0; } case AF_INET6: { struct ipv6_mreq mreq6; memcpy( &mreq6.ipv6mr_multiaddr, &((IP6*) addr)->sin6_addr, 16 ); if( ifce ) { if( (mreq6.ipv6mr_interface = if_nametoindex( ifce )) == 0 ) { log_err( "LPD: Cannot find interface '%s' for multicast: %s", ifce, strerror( errno ) ); return -1; } } else { mreq6.ipv6mr_interface = 0; } if( setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6, sizeof(mreq6)) < 0 ) { log_warn( "LPD: Failed to join IPv6 multicast group: %s", strerror( errno ) ); return -1; } return 0; } default: return -1; } #endif }
int main(int argc, char *argv[]) { int file, sockServer, sockClient; int pos, limit, start; pid_t pid; void *cfg, *sts, *ram; char *name = "/dev/mem"; unsigned long size = 0; struct sockaddr_in addr; uint32_t command = 600000; uint32_t freqMin = 50000; uint32_t freqMax = 50000000; int yes = 1; if((file = open(name, O_RDWR)) < 0) { perror("open"); return 1; } cfg = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, file, 0x40000000); sts = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, file, 0x40001000); ram = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, file, 0x40002000); if((sockServer = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return 1; } setsockopt(sockServer, SOL_SOCKET, SO_REUSEADDR, (void *)&yes , sizeof(yes)); /* setup listening address */ memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(TCP_PORT); if(bind(sockServer, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; } listen(sockServer, 1024); limit = 128; while(!interrupted) { /* enter reset mode */ *((uint32_t *)(cfg + 0)) &= ~7; /* set default phase increment */ *((uint32_t *)(cfg + 4)) = (uint32_t)floor(600000/125.0e6*(1<<30)+0.5); /* set default sample rate */ *((uint32_t *)(cfg + 8)) = 625; /* set default amlitude for test signal */ *((uint32_t *)(cfg + 12)) = 15; /* set default phase increment for test signal */ *((uint32_t *)(cfg + 16)) = (uint32_t)floor((600000 + 100)/125.0e6*(1<<30)+0.5); if((sockClient = accept(sockServer, NULL, NULL)) < 0) { perror("accept"); return 1; } signal(SIGINT, signal_handler); /* enter normal operating mode */ *((uint32_t *)(cfg + 0)) |= 7; while(!interrupted) { ioctl(sockClient, FIONREAD, &size); if(size >= 4) { recv(sockClient, (char *)&command, 4, 0); switch(command >> 31) { case 0: /* set phase increment */ if(command < freqMin || command > freqMax) continue; /* phase increment for down converter */ *((uint32_t *)(cfg + 4)) = (uint32_t)floor(command/125.0e6*(1<<30)+0.5); /* phase increment for test signal */ *((uint32_t *)(cfg + 16)) = (uint32_t)floor((command + 100)/125.0e6*(1<<30)+0.5); break; case 1: /* set sample rate */ switch(command & 3) { case 0: freqMin = 25000; *((uint32_t *)(cfg + 0)) &= ~4; *((uint32_t *)(cfg + 8)) = 1250; *((uint32_t *)(cfg + 0)) |= 4; break; case 1: freqMin = 50000; *((uint32_t *)(cfg + 0)) &= ~4; *((uint32_t *)(cfg + 8)) = 625; *((uint32_t *)(cfg + 0)) |= 4; break; case 2: freqMin = 125000; *((uint32_t *)(cfg + 0)) &= ~4; *((uint32_t *)(cfg + 8)) = 250; *((uint32_t *)(cfg + 0)) |= 4; break; case 3: freqMin = 250000; *((uint32_t *)(cfg + 0)) &= ~4; *((uint32_t *)(cfg + 8)) = 125; *((uint32_t *)(cfg + 0)) |= 4; break; } break; } } /* read ram writer position */ pos = *((uint32_t *)(sts + 0)); /* send 1024 bytes if ready, otherwise sleep 0.1 ms */ if((limit > 0 && pos > limit) || (limit == 0 && pos < 384)) { start = limit > 0 ? limit*8 - 1024 : 3072; if(send(sockClient, ram + start, 1024, 0) < 0) break; limit += 128; if(limit == 512) limit = 0; } else { usleep(100); } } signal(SIGINT, SIG_DFL); close(sockClient); }
/** * main * * executable entry point */ INT __cdecl main(INT argc, CHAR **argv) { int i; int err; int addrlen = sizeof(struct sockaddr); struct sockaddr_in mySockaddr; WSADATA wsaData; HANDLE hReadEvent; DWORD waitResult; /* Thread variable */ HANDLE hThreadClient; DWORD dwThreadClient; DWORD dwClientParam[2]; HANDLE hThreadEvent; /* Sockets descriptor */ const int numSockets = 2; /* number of sockets used in this test */ SOCKET testSockets[2]; /* variable for iocltsocket */ u_long argp; /* Variables needed for setsockopt */ BOOL bReuseAddr = TRUE; /* Variables needed for select */ struct timeval waitTime; fd_set readFds; int socketFds; /* Variables needed for WSARecv */ WSABUF wsaBuf; DWORD dwNbrOfBuf = 1; DWORD dwNbrOfByteSent; DWORD dwRecvFlags = 0; WSAOVERLAPPED wsaRecvOverlapped; /* Variable used to store transmitted data */ unsigned char myBuffer[255]; unsigned char myData[500][255]; unsigned char* pMyData; int bufferCounter; /* Socket DLL version */ const WORD wVersionRequested = MAKEWORD(2,2); /* Sockets initialization to INVALID_SOCKET */ for( i = 0; i < numSockets; i++ ) { testSockets[i] = INVALID_SOCKET; } /* PAL initialization */ if( PAL_Initialize(argc, argv) != 0 ) { return FAIL; } /* Initialize to use winsock2.dll */ err = WSAStartup( wVersionRequested, &wsaData); if(err != 0) { Fail( "Server error: Unexpected failure: " "WSAStartup(%i) " "returned %d\n", wVersionRequested, GetLastError() ); } /* Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports versions greater than 2.2 in addition to 2.2, it will still return 2.2 in wVersion since that is the version we requested. */ if ( wsaData.wVersion != wVersionRequested ) { Trace("Server error: Unexpected failure " "to find a usable version of WinSock DLL\n"); /* Do some cleanup */ DoWSATestCleanup( 0, 0); Fail(""); } /* create an overlapped stream socket in AF_INET domain */ testSockets[0] = WSASocketA( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED ); if( testSockets[0] == INVALID_SOCKET ) { Trace("Server error: Unexpected failure: " "WSASocketA" "(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED)) " " returned %d\n", GetLastError()); /* Do some cleanup */ DoWSATestCleanup( 0, 0); Fail(""); } /* Allows the socket to be bound to an address that is already in use. */ err = setsockopt( testSockets[0], SOL_SOCKET, SO_REUSEADDR, (const char *)&bReuseAddr, sizeof( BOOL ) ); if( err == SOCKET_ERROR ) { Trace("Server error: Unexpected failure: " "setsockopt(.., SOL_SOCKET,SO_REUSEADDR, ..) " "returned %d\n", GetLastError() ); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* enable non blocking socket */ argp=1; err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp); if (err==SOCKET_ERROR ) { Trace("ERROR: Unexpected failure: " "ioctlsocket(.., FIONBIO, ..) " "returned %d\n", GetLastError() ); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* prepare the sockaddr structure */ mySockaddr.sin_family = AF_INET; mySockaddr.sin_port = getRotorTestPort(); mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); memset( &(mySockaddr.sin_zero), 0, 8); /* bind local address to a socket */ err = bind( testSockets[0], (struct sockaddr *)&mySockaddr, sizeof(struct sockaddr) ); if( err == SOCKET_ERROR ) { Trace("ERROR: Unexpected failure: " "bind() socket with local address " "returned %d\n", GetLastError() ); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* listen to the socket */ err = listen( testSockets[0], listenBacklog ); if( err == SOCKET_ERROR ) { Trace("ERROR: Unexpected failure: " "listen() to sockets " "returned %d\n", GetLastError() ); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* Create a Event with initial owner. */ hThreadEvent = CreateEvent( NULL, /* no security */ FALSE, /* reset type */ FALSE, /* initial state */ "EventClientServer" ); /* object name */ if (hThreadEvent == NULL) { /* Check for error. */ Trace( "Server Error: Unexpected failure: " "CreateEvent() " "returned NULL\n"); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* create a client thread */ hThreadClient = CreateThread( NULL, /* no security attributes */ 0, /* use default stack size */ (LPTHREAD_START_ROUTINE)Thread_Client,/* thread function */ (LPVOID)&dwClientParam, /* argument to thread function */ 0, /* use default creation flags */ &dwThreadClient); /* returns the thread identifier*/ if(hThreadClient==NULL) { Trace( "Server Error: Unexpected failure: " "CreateThread() " "returned NULL\n"); CloseEventHandle(hThreadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } if(SetEvent(hThreadEvent)==0) { Trace("Server error: Unexpected failure: " "SetEvent has not set hThreadEvent as expected" "GetLastError returned = %d.\n",GetLastError()); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); CloseEventHandle(hThreadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* set the server waiting time as 10 seconds */ waitTime.tv_sec = 10L; waitTime.tv_usec = 0L; /* initialize the except socket set */ FD_ZERO( &readFds ); /* add socket to readable socket set */ FD_SET( testSockets[0], &readFds ); /* monitor the readable socket set to determine when a connection is ready to be accepted */ socketFds = select( 0, &readFds, NULL, NULL, &waitTime); if( socketFds == SOCKET_ERROR ) { Trace("ERROR: Unexpected failure " "with select\n"); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); CloseEventHandle(hThreadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } if( socketFds == 0 ) { Trace("ERROR: Unexpected select " "timed out\n"); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); CloseEventHandle(hThreadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } if(CloseEventHandle(hThreadEvent)==0) { WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); Fail(""); } /* accept connection */ testSockets[1] = accept( testSockets[0], (struct sockaddr *)&mySockaddr, &addrlen ); if( testSockets[1] == INVALID_SOCKET ) { Trace("ERROR: Unexpected failure: " "accept() connection on socket " "returned %d\n", GetLastError()); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* enable non blocking socket */ argp=1; err = ioctlsocket(testSockets[1], FIONBIO, (u_long FAR *)&argp); if (err==SOCKET_ERROR ) { Trace("ERROR: Unexpected failure: " "ioctlsocket(.., FIONBIO, ..) " "returned %d\n", GetLastError() ); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* create an event */ hReadEvent = CreateEvent( NULL, /* no security */ FALSE, /* reset type */ FALSE, /* initial state */ NULL ); /* object name */ if( hReadEvent == NULL ) { Trace("Server error: Unexpected failure: " "CreateEvent() " "returned %d\n", GetLastError()); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* Initialize the WSABUF structure */ memset(myBuffer, 0, 255); wsaBuf.buf = myBuffer; wsaBuf.len = 255; bufferCounter = 0; pMyData = (unsigned char*)myData; for(i=0;i<500;i++) { /* Initialize the WSAOVERLAPPED to 0 */ memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED)); /* Specify which event to signal when data is arrived*/ wsaRecvOverlapped.hEvent = hReadEvent; /* reset the buffer used by WSARecv */ memset(myBuffer, 0, 255); /* Prepare to receive data */ err = WSARecvFrom( testSockets[1], &wsaBuf, dwNbrOfBuf, &dwNbrOfByteSent, &dwRecvFlags, NULL, NULL, &wsaRecvOverlapped, 0 ); if( err != SOCKET_ERROR ) { ResetEvent(hReadEvent); if(dwNbrOfByteSent==0) { /* Socket as been closed normally */ break; } else { /* no error the server can continue receiving other buffer */ } } else { err = GetLastError(); /* Only WSA_IO_PENDING is expected */ if(err!=WSA_IO_PENDING) { Trace("Server error: WSARecv() " "returned %d, expected WSA_IO_PENDING\n", err ); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); CloseEventHandle(hReadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* Wait 10 seconds for ReadEvent to be signaled from the pending operation */ waitResult = WaitForSingleObject( hReadEvent, 10000 ); if (waitResult!=WAIT_OBJECT_0) { Trace("Server error: Unexpected failure: " "WaitForSingleObject has timed out \n"); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); CloseEventHandle(hReadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } } /* test if data can be copied to the current position in the receiving data array. */ if( pMyData+wsaRecvOverlapped.InternalHigh < &(myData[500][255]) ) { /* copy buffer to data array */ memcpy(pMyData,wsaBuf.buf,wsaRecvOverlapped.InternalHigh); /* increment the position where we can write data on the array*/ pMyData+=wsaRecvOverlapped.InternalHigh; } else { Trace("Server error: Array out of bound " "while writing buffer received in myData.\n"); WaitForClientThreadToFinish(hThreadClient); CloseThreadHandle(hThreadClient); CloseEventHandle(hReadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* Increment bufferCounter to keep track of the number of byte received */ bufferCounter += wsaRecvOverlapped.InternalHigh; } /* end of the for loop */ if(!WaitForClientThreadToFinish(hThreadClient)) { CloseThreadHandle(hThreadClient); CloseEventHandle(hReadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } if(!CloseThreadHandle(hThreadClient)|| !CloseEventHandle(hReadEvent)) { /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } /* verify that all data in the data array are as expected */ pMyData=(unsigned char*)myData; for(i=0;i<bufferCounter;i++) { if(*pMyData!=(i%255)) { Trace("Error comparing received data at position %d" " in data array",i); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); Fail(""); } pMyData++; } /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); PAL_Terminate(); return PASS; }
int main(int argc, char** argv) { FILE* fp = NULL; int sockfd, newsockfd, portno; socklen_t clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } portno = atoi(argv[1]); if (portno <= 0) return record(argv[2]); if (argc > 2) { fp = fopen(argv[2], "wb"); if (fp == NULL) fprintf(stderr, "\nFile for command log has not been open.\n"); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); 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) error("ERROR on binding"); int flag = 1; int result = setsockopt(sockfd, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *) &flag, /* the cast is historical craft */ sizeof(int)); /* length of option value */ if (result < 0) error("ERROR on setting TCP_NODELAY option"); listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); bzero(buffer,256); int fd = serialPort::open_port(PORT_NAME); if (fd == -1) return 1; serialPort::configure_port(fd); setPWM(fd, B_NTR, A_NTR); struct timeval tv; while (true) { n = read(newsockfd, buffer, sizeof(WORD)); if (n < 0) { if (fp != NULL) fclose(fp); error("ERROR reading from socket"); } if (buffer[0] & XINPUT_GAMEPAD_START) { if (fp != NULL) fclose(fp); puts("Received START. Exiting."); break; } printf("Here is the message: %04x\n", (buffer[1] << 8) | buffer[0]); gettimeofday(&tv, NULL); if ( buffer[0] & XINPUT_GAMEPAD_DPAD_DOWN) { printf("DOWN Key pressed\n"); renewB(&tv, false); printf("Now B is %d\n", channelB); } if ( buffer[0] & XINPUT_GAMEPAD_DPAD_UP) { printf("UP Key pressed\n"); renewB(&tv, true); printf("Now B is %d\n", channelB); } if ( buffer[0] & XINPUT_GAMEPAD_DPAD_LEFT) { printf("LEFT Key pressed\n"); renewA(&tv, false); printf("Now A is %d\n", channelA); } if ( buffer[0] & XINPUT_GAMEPAD_DPAD_RIGHT) { printf("RIGHT Key pressed\n"); renewA(&tv, true); printf("Now A is %d\n", channelA); } if ( buffer[0] & ROBOT_STRAIGHT) { printf("STRAIGHT is received\n"); channelA = A_NTR; printf("Now A is %d\n", channelA); } if ( buffer[0] & ROBOT_CONTINUE) { printf("CONTINUE is received\n"); } setPWM(fd, channelB, channelA); if (fp != NULL) { fwrite(&(tv.tv_sec), sizeof(tv.tv_sec), 1, fp); fwrite(&(tv.tv_usec), sizeof(tv.tv_usec), 1, fp); fwrite(buffer, sizeof(WORD), 1, fp); double distance; getDistanceFromSonar(fd, distance); fwrite(&distance, sizeof(double), 1, fp); } } n = write(newsockfd,"I got your message", 18); if (n < 0) error("ERROR writing to socket"); close(newsockfd); close(sockfd); // set defaults setPWM(fd, B_NTR, A_NTR); serialPort::close_port(fd); return 0; }
olibc_retval_t olibc_pak_send (olibc_pak_hdl pak_hdl, int fd, uint32_t offset_bytes) { char *data_buff = NULL; struct iovec iov; struct msghdr smsghdr; struct cmsghdr *scmsgp; uint32_t msg_controllen = 0; u_char cmsgbuf4[CMSG_SPACE((int)sizeof(struct in_pktinfo))]; u_char cmsgbuf6[CMSG_SPACE((int)sizeof(struct in6_pktinfo))]; uint32_t data_sent = 0; memset(&smsghdr, 0, sizeof(smsghdr)); memset(&iov, 0, sizeof(iov)); memset(cmsgbuf4, 0, CMSG_SPACE(sizeof(struct in_pktinfo))); memset(cmsgbuf6, 0, CMSG_SPACE(sizeof(struct in6_pktinfo))); if (!pak_hdl || (fd < 0 )) { olibc_log_error("\nInvalid input"); return OLIBC_RETVAL_INVALID_INPUT; } if (pak_hdl->data_set_flags & OLIBC_DST_SOCKADDR_SET) { smsghdr.msg_name = (caddr_t) &pak_hdl->dst_sock_addr; if (pak_hdl->dst_sock_addr.ss_family == AF_INET) { smsghdr.msg_namelen = sizeof(struct sockaddr_in); } if (pak_hdl->dst_sock_addr.ss_family == AF_INET6) { smsghdr.msg_namelen = sizeof(struct sockaddr_in6); if (pak_hdl->data_set_flags & OLIBC_OUT_IFHNDL_SET) { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &pak_hdl->dst_sock_addr; s6->sin6_scope_id = pak_hdl->out_ifindex; } } } if (pak_hdl->data_set_flags & (OLIBC_OUT_IFHNDL_SET | OLIBC_SRC_SOCKADDR_SET)) { if (pak_hdl->addr_family == AF_INET) { scmsgp = (struct cmsghdr *)cmsgbuf4; scmsgp->cmsg_level = IPPROTO_IP; scmsgp->cmsg_type = IP_PKTINFO; scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo)); } else if (pak_hdl->addr_family == AF_INET6) { struct in6_pktinfo *dst_in6_pkt_info = NULL; scmsgp = (struct cmsghdr *)cmsgbuf6; scmsgp->cmsg_level = IPPROTO_IPV6; scmsgp->cmsg_type = IPV6_PKTINFO; scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo)); dst_in6_pkt_info = (struct in6_pktinfo *)CMSG_DATA(scmsgp); dst_in6_pkt_info->ipi6_ifindex = pak_hdl->out_ifindex; if (pak_hdl->data_set_flags & OLIBC_SRC_SOCKADDR_SET) { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&pak_hdl->dst_sock_addr; memcpy(&dst_in6_pkt_info->ipi6_addr, &s6->sin6_addr, sizeof(struct in6_addr)); } if (pak_hdl->data_set_flags & OLIBC_OUT_IFHNDL_SET) { if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &pak_hdl->out_ifindex, sizeof(pak_hdl->out_ifindex)) < 0) { olibc_log_error("\nFailed to set IPv6 Out IfIndex"); return OLIBC_RETVAL_FAILED; } } } } data_buff = pak_hdl->data_buf + offset_bytes; iov.iov_base = data_buff; iov.iov_len = pak_hdl->data_length - offset_bytes; smsghdr.msg_iov = &iov; smsghdr.msg_iovlen = 1; smsghdr.msg_controllen = msg_controllen; if (msg_controllen) { smsghdr.msg_control = (caddr_t) scmsgp; } data_sent = sendmsg(fd, &smsghdr, 0); if (data_sent != iov.iov_len) { olibc_log_error("\nFailed to send data %d - %d", (int)iov.iov_len, data_sent); return OLIBC_RETVAL_FAILED; } return OLIBC_RETVAL_SUCCESS; }
/* * Create a listening socket on bind_ip:port */ int net_bind( int *fd, const char *bind_ip, int port ) { int n, c[4]; struct sockaddr_in server_addr; #if defined(_WIN32) || defined(_WIN32_WCE) WSADATA wsaData; if( wsa_init_done == 0 ) { if( WSAStartup( MAKEWORD(2,0), &wsaData ) == SOCKET_ERROR ) return( POLARSSL_ERR_NET_SOCKET_FAILED ); wsa_init_done = 1; } #else #if (!defined(__ICCARM__)) && (!defined(__CC_ARM)) && (!defined(__GNUC__)) && (!defined(__TASKING__)) signal( SIGPIPE, SIG_IGN ); #endif #endif if( ( *fd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) < 0 ) return( POLARSSL_ERR_NET_SOCKET_FAILED ); n = 1; setsockopt( *fd, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof( n ) ); server_addr.sin_addr.s_addr = net_htonl( INADDR_ANY ); server_addr.sin_family = AF_INET; server_addr.sin_port = net_htons( port ); if( bind_ip != NULL ) { memset( c, 0, sizeof( c ) ); sscanf( bind_ip, "%d.%d.%d.%d", &c[0], &c[1], &c[2], &c[3] ); for( n = 0; n < 4; n++ ) if( c[n] < 0 || c[n] > 255 ) break; if( n == 4 ) server_addr.sin_addr.s_addr = net_htonl( ( (uint32_t) c[0] << 24 ) | ( (uint32_t) c[1] << 16 ) | ( (uint32_t) c[2] << 8 ) | ( (uint32_t) c[3] ) ); } if( bind( *fd, (struct sockaddr *) &server_addr, sizeof( server_addr ) ) < 0 ) { close( *fd ); return( POLARSSL_ERR_NET_BIND_FAILED ); } if( listen( *fd, POLARSSL_NET_LISTEN_BACKLOG ) != 0 ) { close( *fd ); return( POLARSSL_ERR_NET_LISTEN_FAILED ); } return( 0 ); }
static int identd_ipv6(char *username) { int sok, read_sok, len; char *p; char buf[256]; char outbuf[256]; char ipv6buf[60]; DWORD ipv6buflen = sizeof(ipv6buf); struct sockaddr_in6 addr; sok = socket(AF_INET6, SOCK_STREAM, 0); if (sok == INVALID_SOCKET) { free(username); return 0; } len = 1; setsockopt(sok, SOL_SOCKET, SO_REUSEADDR, (char *)&len, sizeof(len)); memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_port = htons(113); if (bind(sok, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) { closesocket(sok); free(username); return 0; } if (listen(sok, 1) == SOCKET_ERROR) { closesocket(sok); free(username); return 0; } len = sizeof(addr); read_sok = accept(sok, (struct sockaddr *)&addr, &len); closesocket(sok); if (read_sok == INVALID_SOCKET) { free(username); return 0; } identd_ipv6_is_running = FALSE; if (WSAAddressToString((struct sockaddr *)&addr, sizeof(addr), NULL, &ipv6buf, &ipv6buflen) == SOCKET_ERROR) { snprintf(ipv6buf, sizeof(ipv6buf) - 1, "[SOCKET ERROR: 0x%X]", WSAGetLastError()); } snprintf(outbuf, sizeof(outbuf), "%%\tServicing ident request from %s\n", ipv6buf); PrintText(current_sess, outbuf); recv(read_sok, buf, sizeof(buf) - 1, 0); /* buf[sizeof (buf) - 1] = 0; */ /* ensure null termination */ p = strchr(buf, ','); if (p) { snprintf(outbuf, sizeof(outbuf) - 1, "%d, %d : USERID : UNIX : %s\r\n", atoi(buf), atoi(p + 1), username); outbuf[sizeof(outbuf) - 1] = 0; /* ensure null termination */ send(read_sok, outbuf, strlen(outbuf), 0); } sleep(1); closesocket(read_sok); free(username); return 0; }
int socket_set_receive_timeout(cutils_socket_t sock, int timeout_ms) { timeval tv; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); }
int ClientSocket::Connect(const std::string &addr, int port, bool block) throw (utils::Exception) { if (IsConnected()) { Log("Socket is already connected : %d", m_Fd); throw utils::Exception("Socket is already connected"); } Log("connect to %s:%d", addr.c_str(), port); char strPort[10] = { 0 }; sprintf(strPort, "%d", port); // Tell the system what kind(s) of address info we want struct addrinfo addrCriteria; // Criteria for address match memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure addrCriteria.ai_family = AF_UNSPEC; // v4 or v6 is OK addrCriteria.ai_socktype = SOCK_STREAM; // Only streaming sockets addrCriteria.ai_protocol = IPPROTO_TCP; // Only TCP protocol // Get address(es) struct addrinfo *servAddr; // Holder for returned list of server addrs const char* pAddr = addr.size() > 0 ? addr.data() : NULL; int rtnVal = getaddrinfo(pAddr, strPort, &addrCriteria, &servAddr); if (rtnVal != 0 || servAddr == NULL) { Log("getaddrinfo failed, addr=%s:%d, error=%d:%s", pAddr, port, errno, strerror(errno)); return 0 - errno; } int fd = -1; int err = 0; struct addrinfo *addr_info; int nodelay = 1; int keepalive = 1; for (addr_info = servAddr; addr_info != NULL; addr_info = addr_info->ai_next) { // Create a reliable, stream socket using TCP fd = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol); if (fd < 0) { err = errno; continue; // Socket creation failed; try next address } else if ((setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay))) < 0) { Log("nodelay %d failed, errer = %d:%s", fd, errno, strerror(errno)); err = errno; } else if ((setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))) < 0) { Log("keepalive %d failed, errer = %d:%s", fd, errno, strerror(errno)); err = errno; } else if (::connect(fd, addr_info->ai_addr, addr_info->ai_addrlen) < 0) { // Establish the connection to the echo server err = errno; Log("connect %d failed, error=%d:%s", fd, errno, strerror(errno)); } else { err = 0; break; } close(fd); // Socket connection failed; try next address fd = -1; } freeaddrinfo(servAddr); // Free addrinfo allocated in getaddrinfo() if (fd <= 0) { Log("connect failed to %s:%d, error=%d:%s", pAddr, port, err, strerror(err)); return -1; } m_Fd = fd; if (!block) { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); } return fd; }
int Switch_Control::SendResetMessage(const char* phostIp,int iPort) { struct sockaddr_in s_addr; int sockid; socklen_t addr_len; sockid=socket(AF_INET,SOCK_STREAM,0); s_addr.sin_family = AF_INET ; s_addr.sin_addr.s_addr = inet_addr(phostIp) ; s_addr.sin_port=htons((unsigned short)iPort); /* if (-1 == fcntl(sockid, F_SETFL, O_NONBLOCK)) { printf("fcntl socket error!\n"); fflush(stdout); return -1; } */ unsigned long ul = 1; ioctl(sockid, FIONBIO, &ul); //设置为非阻塞模式 struct timeval timeout={3,1000*500}; //1秒 int len = sizeof(timeout); setsockopt(sockid,SOL_SOCKET,SO_SNDTIMEO, &timeout,len); setsockopt(sockid,SOL_SOCKET,SO_RCVTIMEO,&timeout,len); fd_set set; printf("---begin connect \n"); //重复连接3次,防止中断等原因导致的异常 for(int i=0;i<3;i++) { bool ret = false; int iret = -1; iret = connect(sockid,(struct sockaddr *)&s_addr,(int)(sizeof(s_addr))); if(iret == -1) { struct timeval tm; tm.tv_sec = 0; tm.tv_usec = 1000*500; FD_ZERO(&set); FD_SET(sockid, &set); int error=-1; if( select(sockid+1, NULL, &set, NULL, &tm) > 0) { getsockopt(sockid, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len); if(error == 0) { ret = true; printf("---error no \n"); //::close(sockid); //break; } else ret = false; } else ret = false; } else if(iret==0) { break; } if(i==2) { //cout<<"connect Error "<<p_host<<":"<<p_Port<<endl; //perror("::connect"); ::close(sockid); return -1; } printf("---sleeep\n"); usleep(1000); //cout<<"connect again: "<<p_host<<":"<<p_Port<<endl; } int optval = 1; ul = 0; ioctl(sockid, FIONBIO, &ul); //设置为阻塞模式 printf("---connect success \n"); char alivetick[1024]={0}; int iData=0; char strdata[32]={0}; sprintf(strdata,"%d",iData); //发送心跳 Stream ptmpRequest; ptmpRequest.m_clientSocket = sockid; //cJSON *pRet_root; ptmpRequest.pRet_root = cJSON_CreateObject(); ptmpRequest.Requst_Json_str(2,"cmd","reset_device"); ptmpRequest.Requst_Json_str(2,"returnCode","0"); ptmpRequest.Requst_Json_str(2,"serialno","11111111"); ptmpRequest.Send_Jsoon_str(); memset(alivetick,0,sizeof(alivetick)); int length = 0; int i_rc = 0, i_count = 0; int iRecvLen = 0; do { i_rc = recv(sockid, alivetick + i_count, 2000 - i_count, 0); if (i_rc <= 0)break;//异常关闭 i_count += i_rc; } while (strstr(alivetick, "XXEE") == NULL); iRecvLen = i_count; if (iRecvLen <= 0){ ::close(sockid); return -1; } printf("recv:%s \n",alivetick); cJSON *pcmd = NULL; //解析报文数据 replace(alivetick, "XXEE", ""); cJSON* pRoot = cJSON_Parse(alivetick); if (pRoot) { pcmd = cJSON_GetObjectItem(pRoot, "cmd"); if (pcmd) { //判断请求类型 if(strcmp(pcmd->valuestring, "reset_device") == 0) { ::close(sockid); return 0; } } } ::close(sockid); return -1; }