Search Results

Search found 56 results on 3 pages for 'setsockopt'.

Page 1/3 | 1 2 3  | Next Page >

  • setsockopt (sys/socket.h)

    - by lojin
    The prototype for setsockopt is: int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len); Are the following all correct ? Which are not ? a.) int buffsize = 50000; setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&buffsize, sizeof(buffsize)); b.) int buffsize = 50000; setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *)&buffsize, sizeof(buffsize)); c.) char *buffsize = "50000"; setsockopt(s, SOL_SOCKET, SO_RCVBUF, buffsize, strlen(buffsize)); d.) setsockopt(s, SOL_SOCKET, SO_RCVBUF, "50000", 5);

    Read the article

  • setsockopt EOPNOTSUPP (Operation not supported)

    - by brant
    When I strace my MySQL process, I keep finding the same error over and over: setsockopt(240, SOL_IP, IP_TOS, [8], 4) = -1 EOPNOTSUPP (Operation not supported) futex(0x87ab944, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x87ab940, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1 futex(0x87ab260, FUTEX_WAKE_PRIVATE, 1) = 1 select(13, [10 12], NULL, NULL, NULL) = 1 (in [12]) fcntl64(12, F_SETFL, O_RDWR|O_NONBLOCK) = 0 accept(12, {sa_family=AF_FILE, path="\246\32629iE"...}, [2]) = 803 fcntl64(12, F_SETFL, O_RDWR) = 0 getsockname(803, {sa_family=AF_FILE, path="/var/lib/mysql\1"...}, [28]) = 0 fcntl64(803, F_SETFL, O_RDONLY) = 0 fcntl64(803, F_GETFL) = 0x2 (flags O_RDWR) fcntl64(803, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(803, SOL_IP, IP_TOS, [8], 4) = -1 EOPNOTSUPP (Operation not supported) futex(0x87ab944, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x87ab940, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1 futex(0x87ab260, FUTEX_WAKE_PRIVATE, 1) = 1 select(13, [10 12], NULL, NULL, NULL) = 1 (in [12]) fcntl64(12, F_SETFL, O_RDWR|O_NONBLOCK) = 0 accept(12, {sa_family=AF_FILE, path="\246\32629iE"...}, [2]) = 240 fcntl64(12, F_SETFL, O_RDWR) = 0 getsockname(240, {sa_family=AF_FILE, path="/var/lib/mysql\1"...}, [28]) = 0 fcntl64(240, F_SETFL, O_RDONLY) = 0 fcntl64(240, F_GETFL) = 0x2 (flags O_RDWR) fcntl64(240, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(240, SOL_IP, IP_TOS, [8], 4) = -1 EOPNOTSUPP (Operation not supported) When I look for running mysql processes I don't see anything out of the ordinary. I figured it might be someplace in my code, so I modified .htaccess to spit out a 502 error to prevent it from loading anything. The error still shows up, just less frequently. There have been quite a few threads that talk about this error, but no real answer as to how to solve it. my.conf, as per request: [mysqld] #skip-networking #log-slow-queries #safe-show-database #local-infile = 0 log-slow-queries = /var/log/mysql-slow.log max_connections = 200 query_cache_limit = 128643200 key_buffer_size = 1200144000 low_priority_updates = 1 concurrent_insert = 2 thread_cache_size = 7 query_cache_size = 662144000 table_cache = 1600 table_definition_cache = 1024 long_query_time = 2.5 open_files_limit = 2647 max_connect_errors=999999999

    Read the article

  • FTP not listing files behind firewall (setsockopt (ignored): Permission denied)

    - by KennyDs
    We are developing a Magento application that has a module that works with FTP. Today we deployed this on the testing environment which is setup in the following way: Gateway server which has the following iptables rules: # iptables -L -n -v Chain INPUT (policy ACCEPT 2 packets, 130 bytes) pkts bytes target prot opt in out source destination 0 0 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0 165 13720 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED Chain FORWARD (policy ACCEPT 7 packets, 606 bytes) pkts bytes target prot opt in out source destination 0 0 ACCEPT all -- eth1 eth0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 15 965 ACCEPT all -- eth0 eth1 0.0.0.0/0 0.0.0.0/0 0 0 REJECT all -- eth1 eth1 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable Chain OUTPUT (policy ACCEPT 126 packets, 31690 bytes) pkts bytes target prot opt in out source destination These are set at runtime via the following bash script: #!/bin/sh PATH=/usr/sbin:/sbin:/bin:/usr/bin # # delete all existing rules. # iptables -F iptables -t nat -F iptables -t mangle -F iptables -X # Always accept loopback traffic iptables -A INPUT -i lo -j ACCEPT # Allow established connections, and those not coming from the outside iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT iptables -A FORWARD -i eth1 -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT # Allow outgoing connections from the LAN side. iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT # Masquerade. iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE # Don't forward from the outside to the inside. iptables -A FORWARD -i eth1 -o eth1 -j REJECT # Enable routing. echo 1 > /proc/sys/net/ipv4/ip_forward The gateway server is connected to the WAN via eth1 and is connected to the internal network via eth0. One of the servers from eth1 has the following problem when trying to list files over ftp: $ ftp -vd myftpserver.com Connected to myftpserver.com 220 Welcome to MY FTP Server ftp: setsockopt: Bad file descriptor Name (myftpserver.com:magento): XXXXXXXX ---> USER XXXXXXXX 331 User XXXXXXXX, password please Password: ---> PASS XXXX 230 Password Ok, User logged in ---> SYST 215 UNIX Type: L8 Remote system type is UNIX. Using binary mode to transfer files. ftp> ls ftp: setsockopt (ignored): Permission denied ---> PORT 192,168,19,15,135,75 421 Service not available, remote server has closed connection When I try listing the files in passive mode, same result. When I run the same command on the gateway server, everything works fine so I believe that the issue is happening because of the iptables rules not forwarding properly. Does anyone have an idea which rule I need to add to make this work?

    Read the article

  • setsockopt TCP_NODELAY question on Windows Mobile

    - by weki
    Hi all, I have a problem on Windows Mobile 6.0. I would like to create a TCP connection which does not use the Nagle algorithm, so it sends my data when I call "send" function, and does not buffer calls, having too small amount of data. I tried the following: BOOL b = TRUE; setsockopt(socketfd, IPPROTO_TCP, TCP_NODELAY, (char*)(&b), sizeof(BOOL)); It works fine on desktop. But on Windows Mobile, if I set this value, than I make a query for it, the returned value is 8. And the network traffic analysis shows that the nothing changed. Is there any way to force a flush to my socket?

    Read the article

  • What was the motivation for adding the IPV6_V6ONLY flag?

    - by Jeremy Friesner
    In IPv6 networking, the IPV6_V6ONLY flag is used to ensure that a socket will only use IPv6, and in particular that IPv4-to-IPv6 mapping won't be used for that socket. On many OS's, the IPV6_V6ONLY is not set by default, but on some OS's (e.g. Windows 7), it is set by default. My question is: What was the motivation for introducing this flag? Is there something about IPv4-to-IPv6 mapping that was causing problems, and thus people needed a way to disable it? It would seem to me that if someone didn't want to use IPv4-to-IPv6 mapping, they could simply not specify a IPv4-mapped IPv6 address. What am I missing here?

    Read the article

  • See socket options on existing sockets created by other apps?

    - by nailer
    I'd like to test whether particular socket options have been set on an existing socket. Ie, pretty much everything you can see in: #!/usr/bin/env python '''See possible TCP socket options''' import socket sockettypelist = [x for x in dir(socket) if x.startswith('SO_')] sockettypelist.sort() for sockettype in sockettypelist: print sockettype Anyone know how I can see the options on existing sockets, ie those created by other processes? Alas nearly all the documentation I read on Python socket programming is about making new sockets.

    Read the article

  • Strange thing on IPv6 multicast program on Windows

    - by zhanglistar
    I have written an ipv6 multicast program on windows xp sp3. But a problem bothers me a lot. The sendto function implies no error, but I can't capture the packet using wireshark. I am sure the filter is right. Thanks in advance. And the code is as follows: #include "stdafx.h" #include <stdio.h> /* for printf() and fprintf() */ #include <winsock2.h> /* for socket(), connect(), sendto(), and recvfrom() */ #include <ws2tcpip.h> /* for ip_mreq */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <time.h> /* for timestamps */ #include <pcap.h> #include <Iphlpapi.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "wpcap.lib") #pragma comment(lib, "Iphlpapi.lib") int _tmain(int argc, _TCHAR* argv[]) { int sfd; int on, length, iResult; WSADATA wsaData; struct addrinfo Hints; struct addrinfo *multicastAddr, *localAddr; char buf[46]; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } /* Resolve destination address for multicast datagrams */ memset(&Hints, 0, sizeof (Hints)); Hints.ai_family = AF_INET6; Hints.ai_socktype = SOCK_DGRAM; Hints.ai_protocol = IPPROTO_UDP; Hints.ai_flags = AI_NUMERICHOST; iResult = getaddrinfo("FF02::1:2", "547", &Hints, &multicastAddr); if (iResult != 0) { /* error handling */ printf("socket error: %d\n", WSAGetLastError()); return -1; } /* Get a local address with the same family (IPv4 or IPv6) as our multicast group */ Hints.ai_family = multicastAddr->ai_family; Hints.ai_socktype = SOCK_DGRAM; Hints.ai_flags = AI_PASSIVE; /* Return an address we can bind to */ if ( getaddrinfo(NULL, "546", &Hints, &localAddr) != 0 ) { printf("getaddrinfo() failed: %d\n", WSAGetLastError()); exit(-1); } // Create sending socket //sfd = socket (multicastAddr->ai_family, multicastAddr->ai_socktype, multicastAddr->ai_protocol); sfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); if (sfd == -1) { printf("socket error: %d\n", WSAGetLastError()); return 0; } /* Bind to the multicast port */ if ( bind(sfd, localAddr->ai_addr, localAddr->ai_addrlen) != 0 ) { printf("bind() failed: %d\n", WSAGetLastError()); exit(-1); } if (multicastAddr->ai_family == AF_INET6 && multicastAddr->ai_addrlen == sizeof(struct sockaddr_in6)) /* IPv6 */ { on = 1; if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&on, sizeof (on) /*(char *)&interface_addr, sizeof(interface_addr)*/) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; } if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&on, sizeof (on) /*(char *)&interface_addr, sizeof(interface_addr)*/) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; } struct ipv6_mreq multicastRequest; /* Multicast address join structure */ /* Specify the multicast group */ memcpy(&multicastRequest.ipv6mr_multiaddr, &((struct sockaddr_in6*)(multicastAddr->ai_addr))->sin6_addr, sizeof(struct in6_addr)); /* Accept multicast from any interface */ multicastRequest.ipv6mr_interface = 0; /* Join the multicast address */ if ( setsockopt(sfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) { printf("setsockopt() failed: %d\n", WSAGetLastError()); return -1; } on = 1; if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&on, sizeof (on)) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return 0; } } memset(buf, 0, sizeof(buf)); strcpy(buf, "hello world"); iResult = sendto(sfd, buf, strlen(buf), 0, (LPSOCKADDR) multicastAddr->ai_addr, multicastAddr->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; /* Error handling */ } return 0; }

    Read the article

  • MySQL hangs if connection comes from outside the LAN

    - by Subito
    I have a MySQL Server operating just fine if I access him from his local LAN (192.168.100.0/24). If I try to access hin from another LAN (192.168.113.0/24 in this case) it hangs for a really long time before delivering the result. SHOW PROCESSLIST; shows this process in Sleep, State empty. If I strace -p this process I get the following Output (23512 is the PID of the corresponding mysqld process): Process 23512 attached - interrupt to quit restart_syscall(<... resuming interrupted call ...>) = 1 fcntl(10, F_GETFL) = 0x2 (flags O_RDWR) fcntl(10, F_SETFL, O_RDWR|O_NONBLOCK) = 0 accept(10, {sa_family=AF_INET, sin_port=htons(51696), sin_addr=inet_addr("192.168.113.4")}, [16]) = 33 fcntl(10, F_SETFL, O_RDWR) = 0 rt_sigaction(SIGCHLD, {SIG_DFL, [CHLD], SA_RESTORER|SA_RESTART, 0x7f9ce7ca34f0}, {SIG_DFL, [CHLD], SA_RESTORER|SA_RESTART, 0x7f9ce7ca34f0}, ) = 0 getpeername(33, {sa_family=AF_INET, sin_port=htons(51696), sin_addr=inet_addr("192.168.113.4")}, [16]) = 0 getsockname(33, {sa_family=AF_INET, sin_port=htons(3306), sin_addr=inet_addr("192.168.100.190")}, [16]) = 0 open("/etc/hosts.allow", O_RDONLY) = 64 fstat(64, {st_mode=S_IFREG|0644, st_size=580, ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f9ce9839000 read(64, "# /etc/hosts.allow: list of host"..., 4096) = 580 read(64, "", 4096) = 0 close(64) = 0 munmap(0x7f9ce9839000, 4096) = 0 open("/etc/hosts.deny", O_RDONLY) = 64 fstat(64, {st_mode=S_IFREG|0644, st_size=880, ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f9ce9839000 read(64, "# /etc/hosts.deny: list of hosts"..., 4096) = 880 read(64, "", 4096) = 0 close(64) = 0 munmap(0x7f9ce9839000, 4096) = 0 getsockname(33, {sa_family=AF_INET, sin_port=htons(3306), sin_addr=inet_addr("192.168.100.190")}, [16]) = 0 fcntl(33, F_SETFL, O_RDONLY) = 0 fcntl(33, F_GETFL) = 0x2 (flags O_RDWR) setsockopt(33, SOL_SOCKET, SO_RCVTIMEO, "\36\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) = 0 setsockopt(33, SOL_SOCKET, SO_SNDTIMEO, "<\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) = 0 fcntl(33, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(33, SOL_IP, IP_TOS, [8], 4) = 0 setsockopt(33, SOL_TCP, TCP_NODELAY, [1], 4) = 0 futex(0x7f9cea5c9564, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x7f9cea5c9560, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1 futex(0x7f9cea5c6fe0, FUTEX_WAKE_PRIVATE, 1) = 1 poll([{fd=10, events=POLLIN}, {fd=12, events=POLLIN}], 2, -1) = 1 ([{fd=10, revents=POLLIN}]) fcntl(10, F_GETFL) = 0x2 (flags O_RDWR) fcntl(10, F_SETFL, O_RDWR|O_NONBLOCK) = 0 accept(10, {sa_family=AF_INET, sin_port=htons(51697), sin_addr=inet_addr("192.168.113.4")}, [16]) = 31 fcntl(10, F_SETFL, O_RDWR) = 0 rt_sigaction(SIGCHLD, {SIG_DFL, [CHLD], SA_RESTORER|SA_RESTART, 0x7f9ce7ca34f0}, {SIG_DFL, [CHLD], SA_RESTORER|SA_RESTART, 0x7f9ce7ca34f0}, ) = 0 getpeername(31, {sa_family=AF_INET, sin_port=htons(51697), sin_addr=inet_addr("192.168.113.4")}, [16]) = 0 getsockname(31, {sa_family=AF_INET, sin_port=htons(3306), sin_addr=inet_addr("192.168.100.190")}, [16]) = 0 open("/etc/hosts.allow", O_RDONLY) = 33 fstat(33, {st_mode=S_IFREG|0644, st_size=580, ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f9ce9839000 read(33, "# /etc/hosts.allow: list of host"..., 4096) = 580 read(33, "", 4096) = 0 close(33) = 0 munmap(0x7f9ce9839000, 4096) = 0 open("/etc/hosts.deny", O_RDONLY) = 33 fstat(33, {st_mode=S_IFREG|0644, st_size=880, ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f9ce9839000 read(33, "# /etc/hosts.deny: list of hosts"..., 4096) = 880 read(33, "", 4096) = 0 close(33) = 0 munmap(0x7f9ce9839000, 4096) = 0 getsockname(31, {sa_family=AF_INET, sin_port=htons(3306), sin_addr=inet_addr("192.168.100.190")}, [16]) = 0 fcntl(31, F_SETFL, O_RDONLY) = 0 fcntl(31, F_GETFL) = 0x2 (flags O_RDWR) setsockopt(31, SOL_SOCKET, SO_RCVTIMEO, "\36\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) = 0 setsockopt(31, SOL_SOCKET, SO_SNDTIMEO, "<\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) = 0 fcntl(31, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(31, SOL_IP, IP_TOS, [8], 4) = 0 setsockopt(31, SOL_TCP, TCP_NODELAY, [1], 4) = 0 futex(0x7f9cea5c9564, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x7f9cea5c9560, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1 futex(0x7f9cea5c6fe0, FUTEX_WAKE_PRIVATE, 1) = 1 poll([{fd=10, events=POLLIN}, {fd=12, events=POLLIN}], 2, -1^C <unfinished ...> Process 23512 detached This output repeats itself until the answer gets send. It could take up to 15 Minutes until the request gets served. In the local LAN its a matter of Milliseconds. Why is this and how can I debug this further? [Edit] tcpdump shows a ton of this: 14:49:44.103107 IP cassandra-test.mysql > 192.168.X.6.64626: Flags [S.], seq 1434117703, ack 1793610733, win 14600, options [mss 1460,nop,nop,sackOK,nop,wscale 7], length 0 14:49:44.135187 IP 192.168.X.6.64625 > cassandra-test.mysql: Flags [P.], seq 106:145, ack 182, win 4345, length 39 14:49:44.135293 IP cassandra-test.mysql > 192.168.X.6.64625: Flags [P.], seq 182:293, ack 145, win 115, length 111 14:49:44.167025 IP 192.168.X.6.64624 > cassandra-test.mysql: Flags [.], ack 444, win 4280, length 0 14:49:44.168933 IP 192.168.X.6.64626 > cassandra-test.mysql: Flags [.], ack 1, win 4390, length 0 14:49:44.169088 IP cassandra-test.mysql > 192.168.X.6.64626: Flags [P.], seq 1:89, ack 1, win 115, length 88 14:49:44.169672 IP 192.168.X.6.64625 > cassandra-test.mysql: Flags [P.], seq 145:171, ack 293, win 4317, length 26 14:49:44.169726 IP cassandra-test.mysql > 192.168.X.6.64625: Flags [P.], seq 293:419, ack 171, win 115, length 126 14:49:44.275111 IP 192.168.X.6.64626 > cassandra-test.mysql: Flags [P.], seq 1:74, ack 89, win 4368, length 73 14:49:44.275131 IP cassandra-test.mysql > 192.168.X.6.64626: Flags [.], ack 74, win 115, length 0 14:49:44.275149 IP 192.168.X.6.64625 > cassandra-test.mysql: Flags [P.], seq 171:180, ack 419, win 4286, length 9 14:49:44.275189 IP cassandra-test.mysql > 192.168.X.6.64626: Flags [P.], seq 89:100, ack 74, win 115, length 11 14:49:44.275264 IP 192.168.X.6.64625 > cassandra-test.mysql: Flags [P.], seq 180:185, ack 419, win 4286, length 5 14:49:44.275281 IP cassandra-test.mysql > 192.168.X.6.64625: Flags [.], ack 185, win 115, length 0 14:49:44.275295 IP cassandra-test.mysql > 192.168.X.6.64625: Flags [F.], seq 419, ack 185, win 115, length 0 14:49:44.275650 IP 192.168.X.6.64625 > cassandra-test.mysql: Flags [F.], seq 185, ack 419, win 4286, length 0 14:49:44.275660 IP cassandra-test.mysql > 192.168.X.6.64625: Flags [.], ack 186, win 115, length 0 14:49:44.275910 IP 192.168.X.6.64627 > cassandra-test.mysql: Flags [S], seq 2336421549, win 8192, options [mss 1351,nop,wscale 2,nop,nop,sackOK], length 0 14:49:44.275921 IP cassandra-test.mysql > 192.168.X.6.64627: Flags [S.], seq 3289359778, ack 2336421550, win 14600, options [mss 1460,nop,nop,sackOK,nop,wscale 7], length 0

    Read the article

  • How to limit traffic using multicast over localhost

    - by Shane Holloway
    I'm using multicast UDP over localhost to implement a loose collection of cooperative programs running on a single machine. The following code works well on Mac OSX, Windows and linux. The flaw is that the code will receive UDP packets outside of the localhost network as well. For example, sendSock.sendto(pkt, ('192.168.0.25', 1600)) is received by my test machine when sent from another box on my network. import platform, time, socket, select addr = ("239.255.2.9", 1600) sendSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sendSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 24) sendSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton("127.0.0.1")) recvSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) recvSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) if hasattr(socket, 'SO_REUSEPORT'): recvSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, True) recvSock.bind(("0.0.0.0", addr[1])) status = recvSock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr[0]) + socket.inet_aton("127.0.0.1")); while 1: pkt = "Hello host: {1} time: {0}".format(time.ctime(), platform.node()) print "SEND to: {0} data: {1}".format(addr, pkt) r = sendSock.sendto(pkt, addr) while select.select([recvSock], [], [], 0)[0]: data, fromAddr = recvSock.recvfrom(1024) print "RECV from: {0} data: {1}".format(fromAddr, data) time.sleep(2) I've attempted to recvSock.bind(("127.0.0.1", addr[1])), but that prevents the socket from receiving any multicast traffic. Is there a proper way to configure recvSock to only accept multicast packets from the 127/24 network, or do I need to test the address of each received packet?

    Read the article

  • Webserver max CPU when apache and MYSQL are ran together

    - by Tim
    This website has been running fine without issues, Recently it went down. After some investigation it looks like the combo of MYSQL and Apache bring the box to its knees. Apache can run find serving static web pages and MYSQL can run fine when the website isn't working. As soon as the website is enabled with SQL running the CPU on the box remains at 100%. Picture of the usage: http://i.stack.imgur.com/GG2NC.png I've checked the sql database for errors, tried tuning nearly every parameter in apache/sql's conf file for performance. The server is a redhat based box running the latest software packages. Any help/suggestions are welcome. Doing an strace on a high cpu apache process I see the following: read(14, "", 8192) = 0 close(14) = 0 socket(PF_FILE, SOCK_STREAM, 0) = 14 fcntl64(14, F_SETFL, O_RDONLY) = 0 fcntl64(14, F_GETFL) = 0x2 (flags O_RDWR) connect(14, {sa_family=AF_FILE, path="/var/lib/mysql/mysql.sock"...}, 110) = 0 setsockopt(14, SOL_SOCKET, SO_RCVTIMEO, "\2003\341\1\0\0\0\0", 8) = 0 setsockopt(14, SOL_SOCKET, SO_SNDTIMEO, "\2003\341\1\0\0\0\0", 8) = 0 setsockopt(14, SOL_IP, IP_TOS, [8], 4) = -1 EOPNOTSUPP (Operation not supported) setsockopt(14, SOL_SOCKET, SO_KEEPALIVE, [1], 4) = 0 Here is what I see from a mysql process: futex(0x86fc9a4, FUTEX_WAIT_PRIVATE, 39, NULL) = 0 futex(0x86fc734, FUTEX_WAIT_PRIVATE, 2, NULL) = 0 futex(0x86fc734, FUTEX_WAKE_PRIVATE, 1) = 0 gettimeofday({1301465020, 141613}, NULL) = 0 clock_gettime(CLOCK_REALTIME, {1301465020, 141699633}) = 0 futex(0x8707a64, FUTEX_WAIT_PRIVATE, 1, {4, 999913367}) = 0 futex(0x8707a40, FUTEX_WAIT_PRIVATE, 2, NULL) = 0 futex(0x8707a40, FUTEX_WAKE_PRIVATE, 1) = 0 exit_group(0) = ?

    Read the article

  • XML Socket and Regular Socket in Flash/Flex does not send message immediately.

    - by kramer
    I am trying to build a basic RIA where my Flex application client opens an XML socket, sends the xml message "people_list" to server, and prints out the response. I have ruby at the server side and I have successfully set up the security policy stuff. The ruby xml server, successfully accepts the connections from Flex, successfully detects when they are closed and can also send messages to client. But; there is a problem... It cannot receive messages from flex client. The messages sent from flex client are queued and sent as one package when the socket is closed. Therefore, the whole wait-for-request-then-reply thing is not working... This is also -kinda- mentioned in the XMLSocket.send() document, where it is stated that the messages are sent async so; they may be delivered at any time in future. But; I need them to be synced, flushed or whatever. This is the server side code: require 'socket' require 'observer' class Network_Reader_Ops include Observable @@reader_listener_socket = UDPSocket.new @@reader_broadcast_socket = UDPSocket.new @@thread_id def initialize @@reader_broadcast_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, 1) @@reader_broadcast_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) @@reader_listener_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) @@reader_broadcast_socket.bind('', 50050) @@reader_listener_socket.bind('', 50051) @@thread_id = Thread.start do loop do begin text, sender = @@reader_listener_socket.recvfrom_nonblock 1024 print("Knock response recived: ", text) notify_observers text rescue Errno::EAGAIN retry rescue Errno::EWOULDBLOCK retry end end end end def query @@reader_broadcast_socket.send("KNOCK KNOCK", 0, "255.255.255.255", 50050) end def stop Thread.kill @@thread_id end end class XMLSocket_Connection attr_accessor :connection_id def update (data) connection_id.write(data+"\0") end end begin # Set EOL for Flash $/ = '\x00' xml_socket = TCPServer.open('', '4444') security_policy_socket = TCPServer.open('', '843') xml_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) security_policy_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) a = Thread.start do network_ops = nil loop { accepted_connection = xml_socket.accept print(accepted_connection.peeraddr, " is accepted\n") while accepted_connection.gets incoming = $_.dump print("Received: ", incoming) if incoming == "<request>readers on network</request>" then network_ops = Network_Reader_Ops.new this_con = XMLSocket_Connection.new this_con.connection_id = accepted_connection network_ops.add_observer this_con network_ops.query end end if not network_ops.nil? then network_ops.delete_observer this_con network_ops.stop network_ops = nil end print(accepted_connection, " is gone\n") accepted_connection.close } end b = Thread.start do loop { accepted_connection = security_policy_socket.accept Thread.start do current_connection = accepted_connection while current_connection.gets if $_ =~ /.*policy\-file.*/i then current_connection.write("<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\0") end end current_connection.close end } end a.join b.join rescue puts "FAILED" retry end And this is the flex/flash client side code: UPDATE: I have also tried using regular socket and calling flush() method but; the result was same. private var socket:XMLSocket = new XMLSocket(); protected function stopXMLSocket():void { socket.close(); } protected function startXMLSocket():void { socket.addEventListener(DataEvent.DATA, dataHandler); socket.connect(xmlSocketServer_address, xmlSocketServer_port); socket.send("<request>readers on network</request>"); } protected function dataHandler(event:DataEvent):void { mx.controls.Alert.show(event.data); } How do I achieve the described behaviour?

    Read the article

  • Extremely high mysqld CPU usage with no active queries

    - by RadarNyan
    I have a VPS running Ubuntu 12.04 LTS with LEMP stack, followed the guide from Linode Library (since I'm using a Linode) to setup, and everything worked fine until now. I don't know what's wrong, but my CPU usage just goes up since a week ago. Today things getting really bad - I got 74% CPU usage so I went check and found that mysqld taking too much CPU usage (somewhere around 30% ~ 80%) So I did some Google Search, tried disable InnoDB, restart mysql, reset ntp / system clock (Isn't this bug supposed to happen more than a year ago?!) and reboot my VPS, nothing helped. Even with mysql processlist empty, I still get mysqld CPU usage very high. I don't know what I missed and have totally no idea, any advice would be appreciated. Thanks in advance. Update: I got these from running "strace mysqld" write(2, "InnoDB: Unable to lock ./ibdata1"..., 44) = 44 write(2, "InnoDB: Check that you do not al"..., 115) = 115 select(0, NULL, NULL, NULL, {1, 0}^[[A^[[A) = 0 (Timeout) fcntl64(3, F_SETLK64, {type=F_WRLCK, whence=SEEK_SET, start=0, len=0}, 0xbfa496f8) = -1 EAGAIN (Resource temporarily unavailable) hum... I did tried to disable InnoDB and it didn't fix this problem. Any idea? Update2: # ps -e | grep mysqld 13099 ? 00:00:20 mysqld then use "strace -p 13099", the following lines appears repeatedly: fcntl64(12, F_GETFL) = 0x2 (flags O_RDWR) fcntl64(12, F_SETFL, O_RDWR|O_NONBLOCK) = 0 accept(12, {sa_family=AF_FILE, NULL}, [2]) = 14 fcntl64(12, F_SETFL, O_RDWR) = 0 getsockname(14, {sa_family=AF_FILE, path="/var/run/mysqld/mysqld.sock"}, [30]) = 0 fcntl64(14, F_SETFL, O_RDONLY) = 0 fcntl64(14, F_GETFL) = 0x2 (flags O_RDWR) setsockopt(14, SOL_SOCKET, SO_RCVTIMEO, "\36\0\0\0\0\0\0\0", 8) = 0 setsockopt(14, SOL_SOCKET, SO_SNDTIMEO, "<\0\0\0\0\0\0\0", 8) = 0 fcntl64(14, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(14, SOL_IP, IP_TOS, [8], 4) = -1 EOPNOTSUPP (Operation not supported) futex(0xb786a584, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0xb786a580, {FUTEX_OP_SET, 0, FUTEX_OP_CMP_GT, 1}) = 1 futex(0xb7869998, FUTEX_WAKE_PRIVATE, 1) = 1 poll([{fd=10, events=POLLIN}, {fd=12, events=POLLIN}], 2, -1) = 1 ([{fd=12, revents=POLLIN}]) er... now I totally don't get it x_x help

    Read the article

  • Router Alert options on IGMPv2 packets

    - by Scakko
    I'm trying to forge an IGMPv2 Membership Request packet and send it on a RAW socket. The RFC 3376 states: IGMP messages are encapsulated in IPv4 datagrams, with an IP protocol number of 2. Every IGMP message described in this document is sent with an IP Time-to-Live of 1, IP Precedence of Internetwork Control (e.g., Type of Service 0xc0), and carries an IP Router Alert option [RFC-2113] in its IP header So the IP_ROUTER_ALERT flag must be set. I'm trying to forge the strict necessary of the packet (e.g. only the IGMP header & payload), so i'm using the setsockopt to edit the IP options. some useful variables: #define C_IP_MULTICAST_TTL 1 #define C_IP_ROUTER_ALERT 1 int sockfd = 0; int ecsockopt = 0; int bytes_num = 0; int ip_multicast_ttl = C_IP_MULTICAST_TTL; int ip_router_alert = C_IP_ROUTER_ALERT; Here's how I open the RAW socket: sock_domain = AF_INET; sock_type = SOCK_RAW; sock_proto = IPPROTO_IGMP; if ((ecsockopt = socket(sock_domain,sock_type,sock_proto)) < 0) { printf("Error %d: Can't open socket.\n", errno); return 1; } else { printf("** Socket opened.\n"); } sockfd = ecsockopt; Then I set the TTL and Router Alert option: // Set the sent packets TTL if((ecsockopt = setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ip_multicast_ttl, sizeof(ip_multicast_ttl))) < 0) { printf("Error %d: Can't set TTL.\n", ecsockopt); return 1; } else { printf("** TTL set.\n"); } // Set the Router Alert if((ecsockopt = setsockopt(sockfd, IPPROTO_IP, IP_ROUTER_ALERT, &ip_router_alert, sizeof(ip_router_alert))) < 0) { printf("Error %d: Can't set Router Alert.\n", ecsockopt); return 1; } else { printf("** Router Alert set.\n"); } The setsockopt of IP_ROUTER_ALERT returns 0. After forging the packet, i send it with sendto in this way: // Send the packet if((bytes_num = sendto(sockfd, packet, packet_size, 0, (struct sockaddr*) &mgroup1_addr, sizeof(mgroup1_addr))) < 0) { printf("Error %d: Can't send Membership report message.\n", bytes_num); return 1; } else { printf("** Membership report message sent. (bytes=%d)\n",bytes_num); } The packet is sent, but the IP_ROUTER_ALERT option (checked with wireshark) is missing. Am i doing something wrong? is there some other methods to set the IP_ROUTER_ALERT option? Thanks in advance.

    Read the article

  • I was stuck in implementing Simple Ftp with Winsock [migrated]

    - by user67449
    I want to implement a SimpleFtp with Winsock. But I was stuck in the maybe the file stream reading and writing. This is the Server. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } void SockBind(SOCKET sock, int port, sockaddr_in &addrsock){ addrsock.sin_family=AF_INET; addrsock.sin_port=htons(port); addrsock.sin_addr.S_un.S_addr=htonl(INADDR_ANY); if( bind(sock, (sockaddr*)&addrsock, sizeof(addrsock)) == SOCKET_ERROR ){ cout<<"Error at bind(). Error: "<<GetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } void SockListen(SOCKET sock, int bak){ int err=listen(sock, bak); if(err==SOCKET_ERROR){ cout<<"Error at listen()."<<WSAGetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } int SockSend(DataPack &dataPack, SOCKET sock, char *sockBuf){ int bytesLeft=0, bytesSend=0; int idx=0; bytesLeft=sizeof(dataPack); // ?DataPack?????sockBuf??? memcpy(sockBuf, &dataPack, sizeof(dataPack)); while(bytesLeft>0){ bytesSend=send(sock, &sockBuf[idx], bytesLeft, 0); if(bytesSend==SOCKET_ERROR){ cout<<"Error at send()."<<endl; return 1; } bytesLeft-=bytesSend; idx+=bytesSend; } return 0; } int GetFileLen(FILE *fp){ // ?????? if(fp==NULL){ cout<<"Invalid argument. Error at GetFileLen()."<<endl; exit(0); } fseek(fp, 0, SEEK_END); int tempFileLen=ftell(fp); fseek(fp, 0, SEEK_SET); return tempFileLen; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockListen==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Bind the socket. SockBind(sockListen, port, addrServ); // Listen for incoming connection requests cout<<"Waiting for incoming connection requests..."<<endl; SockListen(sockListen, 5); // Accept the connection request. sockaddr_in addrClient; int len=sizeof(addrClient); SOCKET sockConn=accept(sockListen, (sockaddr*)&addrClient, &len); if(sockConn!=INVALID_SOCKET){ cout<<"Connected to client successfully."<<endl; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at setsockopt(). ?socket????????"<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } //------------------------------------------------------------------------// DataPack dataPackSend; memset(&dataPackSend, 0, sizeof(dataPackSend)); int bytesRead; int bytesLeft; int bytesSend; int packCount; // Counts how many DataPack needed FILE *frp; // Used to read if(strcpy_s(dataPackSend.fName, "music.mp3")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } // Open the file in read+binary mode err=fopen_s(&frp, dataPackSend.fName, "rb"); if(err!=0){ cout<<"Error at fopen_s()."<<endl; return 1; } char fileBuf[FILE_BUFFER_SIZE]; // Set the buffer size of File if(setvbuf(frp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } // Get file's length int fileLen=GetFileLen(frp); cout<<"File ???:"<<fileLen<<" bytes."<<endl; // Calculate how many DataPacks needed packCount=ceil( (double)fileLen/CONTENT_SIZE ); cout<<"File Length: "<<fileLen<<" "<<"Content Size: "<<CONTENT_SIZE<<endl; cout<<"???"<<packCount<<" ?DataPack"<<endl; int i=0; for(i=0; i<packCount; i++){ //?????dataPackSend????? memset(&dataPackSend, 0, sizeof(dataPackSend)); // Fill the dataPackSend if(strcpy_s(dataPackSend.fName, "abc.txt")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } dataPackSend.packLen=DATA_PACK_SIZE; dataPackSend.fLen=fileLen; dataPackSend.packCount=packCount; if( packCount==1 ){ //??DataPack??? bytesRead=fread(fileBuf, 1, dataPackSend.fLen, frp); dataPackSend.contenLen=dataPackSend.fLen; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=0; //???????DataPack // ?????dataPackSend?Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack"<<endl; } }else if( packCount>1 && i<(packCount-1) ){ // ???(???????) bytesRead=fread(fileBuf, 1, CONTENT_SIZE, frp); dataPackSend.contenLen=CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend??????Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } }else{ // ????? bytesRead=fread(fileBuf, 1, (dataPackSend.fLen-i*CONTENT_SIZE), frp); dataPackSend.contenLen=dataPackSend.fLen-i*CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend???Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } } } fclose(frp); closesocket(sockListen); closesocket(sockConn); WSACleanup(); return 0; } And this is Client. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; //DataPack??? int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } int SockRecv(SOCKET sock, char *sockBuf){ int bytesLeft, bytesRecv; int idx=0; bytesLeft=DATA_PACK_SIZE; while(bytesLeft>0){ bytesRecv=recv(sock, &sockBuf[idx], bytesLeft, 0); if(bytesRecv==SOCKET_ERROR){ cout<<"Error at recv()."<<endl; return 1; } bytesLeft-=bytesRecv; idx+=bytesRecv; } return 0; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockClient=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockClient==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at getsockopt(). ?socket????????"<<endl; closesocket(sockClient); WSACleanup(); exit(0); } // Connect to the Server addrServ.sin_family=AF_INET; addrServ.sin_port=htons(port); addrServ.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); err=connect(sockClient, (sockaddr*)&addrServ, sizeof(sockaddr)); if(err==SOCKET_ERROR){ cout<<"Error at connect()."<<GetLastError()<<endl; closesocket(sockClient); WSACleanup(); return 1; }else{ cout<<"Connected to the FTP Server successfully."<<endl; } /* int i=0; int bytesRecv, bytesLeft, bytesWrite; int packCount=0, fLen=0; DataPack dataPackRecv; //?????? SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; cout<<"?DataPack??fName????: "<<dataPackRecv.fName<<endl; //??????? packCount=dataPackRecv.packCount; cout<<"?? "<<packCount<<" ?DataPack."<<endl; fLen=dataPackRecv.fLen; // Create a local file to write into FILE *fwp; err=fopen_s(&fwp, dataPackRecv.fName, "wb"); if(err!=0){ cout<<"Error at creat fopen_s(). Failed to create a local file to write into."<<endl; return 1; } // Set the buffer size of File char fileBuf[FILE_BUFFER_SIZE]; if(setvbuf(fwp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; memset(fileBuf, 0, sizeof(fileBuf)); closesocket(sockClient); WSACleanup(); exit(0); } //???????content???? memcpy(fileBuf, dataPackRecv.content, sizeof(dataPackRecv.content)); bytesWrite=fwrite(fileBuf, 1, sizeof(fileBuf), fwp); if(bytesWrite<sizeof(fileBuf)){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } //?????packCount-1????????????????? for(int i=1; i<packCount; i++){ // ????????? memset(sockBuf, 0, sizeof(sockBuf)); memset(&dataPackRecv, 0, sizeof(dataPackRecv)); memset(fileBuf, 0, sizeof(fileBuf)); SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; //???? memcpy(fileBuf, dataPackRecv.content, dataPackRecv.contenLen); bytesWrite=fwrite(fileBuf, 1, dataPackRecv.contenLen, fwp); if(bytesWrite<dataPackRecv.contenLen){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } } if( (i+1)==packCount ){ cout<<"??DataPack????????!"<<endl; } fclose(fwp); closesocket(sockClient); WSACleanup(); return 0;*/ }

    Read the article

  • When binding a client TCP socket to a specific local port with Winsock, SO_REUSEADDR does not have a

    - by Checkers
    I'm binding a client TCP socket to a specific local port. To handle the situation where the socket remains in TIME_WAIT state for some time, I use setsockopt() with SO_REUSEADDR on a socket. It works on Linux, but does not work on Windows, I get WSAEADDRINUSE on connect() call when the previous connection is still in TIME_WAIT. MSDN is not exactly clear what should happen with client sockets: [...] For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need not call bind at all—connect chooses an unused port automatically. [...] How do I avoid this?

    Read the article

  • C, Linux: Receiving data from multiple multicast address on same port - how to distinguish them?

    - by Gigi
    2 vote down star I have an application that is receiving data from multiple multicast sources on the same port. I am able to receive the data. However, I am trying to account for statistics of each group (i.e. msgs received, bytes received) and all the data is getting mixed up. Does anyone know how to solved this problem? If I try to look at the sender's address, it is not the multicast address, but rather the IP of the sending machine. I am using the following socket options: struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = inet_addr("224.1.2.3"); mreq.imr_interface.s_addr = INADDR_ANY; setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); and also: setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse)); I appreciate any help!!!

    Read the article

  • Receving multiple multicast feeds on the same port - C, Linux

    - by Gigi
    I have an application that is receiving data from multiple multicast sources on the same port. I am able to receive the data. However, I am trying to account for statistics of each group (i.e. msgs received, bytes received) and all the data is getting mixed up. Does anyone know how to solved this problem? If I try to look at the sender's address, it is not the multicast address, but rather the IP of the sending machine. I am using the following socket options: struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = inet_addr("224.1.2.3"); mreq.imr_interface.s_addr = INADDR_ANY; setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); and also: setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse)); I appreciate any help!!!

    Read the article

  • Receiving broadcast packets using packet socket

    - by user314336
    Hello I try to send DHCP RENEW packets to the network and receive the responses. I broadcast the packet and I can see that it's successfully sent using Wireshark. But I have difficulties receiving the responses.I use packet sockets to catch the packets. I can see that there are responses to my RENEW packet using Wireshark, but my function 'packet_receive_renew' sometimes catch the packets but sometimes it can not catch the packets. I set the file descriptor using FDSET but the 'select' in my code can not realize that there are new packets for that file descriptor and timeout occurs. I couldn't make it clear that why it sometimes catches the packets and sometimes doesn't. Anybody have an idea? Thanks in advance. Here's the receive function. int packet_receive_renew(struct client_info* info) { int fd; struct sockaddr_ll sock, si_other; struct sockaddr_in si_me; fd_set rfds; struct timeval tv; time_t start, end; int bcast = 1; int ret = 0, try = 0; char buf[1500] = {'\0'}; uint8_t tmp[BUFLEN] = {'\0'}; struct dhcp_packet pkt; socklen_t slen = sizeof(si_other); struct dhcps* new_dhcps; memset((char *) &si_me, 0, sizeof(si_me)); memset((char *) &si_other, 0, sizeof(si_other)); memset(&pkt, 0, sizeof(struct dhcp_packet)); define SERVER_AND_CLIENT_PORTS ((67 << 16) + 68) static const struct sock_filter filter_instr[] = { /* check for udp */ BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9), BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 4), /* L5, L1, is UDP? */ /* skip IP header */ BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0), /* L5: */ /* check udp source and destination ports */ BPF_STMT(BPF_LD|BPF_W|BPF_IND, 0), BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, SERVER_AND_CLIENT_PORTS, 0, 1), /* L3, L4 */ /* returns */ BPF_STMT(BPF_RET|BPF_K, 0x0fffffff ), /* L3: pass */ BPF_STMT(BPF_RET|BPF_K, 0), /* L4: reject */ }; static const struct sock_fprog filter_prog = { .len = sizeof(filter_instr) / sizeof(filter_instr[0]), /* casting const away: */ .filter = (struct sock_filter *) filter_instr, }; printf("opening raw socket on ifindex %d\n", info->interf.if_index); if (-1==(fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP)))) { perror("packet_receive_renew::socket"); return -1; } printf("got raw socket fd %d\n", fd); /* Use only if standard ports are in use */ /* Ignoring error (kernel may lack support for this) */ if (-1==setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog))) perror("packet_receive_renew::setsockopt"); sock.sll_family = AF_PACKET; sock.sll_protocol = htons(ETH_P_IP); //sock.sll_pkttype = PACKET_BROADCAST; sock.sll_ifindex = info->interf.if_index; if (-1 == bind(fd, (struct sockaddr *) &sock, sizeof(sock))) { perror("packet_receive_renew::bind"); close(fd); return -3; } if (-1 == setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(bcast))) { perror("packet_receive_renew::setsockopt"); close(fd); return -1; } FD_ZERO(&rfds); FD_SET(fd, &rfds); tv.tv_sec = TIMEOUT; tv.tv_usec = 0; ret = time(&start); if (-1 == ret) { perror("packet_receive_renew::time"); close(fd); return -1; } while(1) { ret = select(fd + 1, &rfds, NULL, NULL, &tv); time(&end); if (TOTAL_PENDING <= (end - start)) { fprintf(stderr, "End receiving\n"); break; } if (-1 == ret) { perror("packet_receive_renew::select"); close(fd); return -4; } else if (ret) { new_dhcps = (struct dhcps*)calloc(1, sizeof(struct dhcps)); if (-1 == recvfrom(fd, buf, 1500, 0, (struct sockaddr*)&si_other, &slen)) { perror("packet_receive_renew::recvfrom"); close(fd); return -4; } deref_packet((unsigned char*)buf, &pkt, info); if (-1!=(ret=get_option_val(pkt.options, DHO_DHCP_SERVER_IDENTIFIER, tmp))) { sprintf((char*)tmp, "%d.%d.%d.%d", tmp[0],tmp[1],tmp[2],tmp[3]); fprintf(stderr, "Received renew from %s\n", tmp); } else { fprintf(stderr, "Couldnt get DHO_DHCP_SERVER_IDENTIFIER%s\n", tmp); close(fd); return -5; } new_dhcps->dhcps_addr = strdup((char*)tmp); //add to list if (info->dhcps_list) info->dhcps_list->next = new_dhcps; else info->dhcps_list = new_dhcps; new_dhcps->next = NULL; } else { try++; tv.tv_sec = TOTAL_PENDING - try * TIMEOUT; tv.tv_usec = 0; fprintf(stderr, "Timeout occured\n"); } } close(fd); printf("close fd:%d\n", fd); return 0; }

    Read the article

  • Increase the TCP receive window for a specific socket

    - by rursw1
    Hi, How to increase the TCP receive window for a specific socket? - I know how to do so for all the sockets by setting the registry key TcpWindowSize, but how do do that for a specific one? According to MSFT's documents, the way is Calling the Windows Sockets function setsockopt, which sets the receive window on a per-socket basis. But in setsockopt, it is mentioned about SO_RCVBUF : Specifies the total per-socket buffer space reserved for receives. This is unrelated to SO_MAX_MSG_SIZE and does not necessarily correspond to the size of the TCP receive window. So is it possible? How? Thanks.

    Read the article

  • Increase a recive buffer in UDP socket

    - by unresolved_external
    I'wm writing an app, which transmits video and obviously uses UDP protocol fot this purpose. So I am wondering how can I increase a size of send/recieve buffer, cause currently the maximal size of data, which I can send is 65000 bytes. I already tried to do it in following way: int option = 262144; if(setsockopt(m_SocketHandle,SOL_SOCKET,SO_RCVBUF ,(char*)&option,sizeof(option)) < 0) { printf("setsockopt failed\n"); } But it did not work. So how can I do it?

    Read the article

  • packet mmap send packet format

    - by SeregASM
    I want to improve packet transmitting performance. Before that I used raw sockets and now I study packet_mmap. I have packets(frames) which I already captured from kernel module from another PC, put to current PC and now I want to retransmit them to local interface with following forwarding. I have got example of packet_mmap, integrated it to my project, but I send fd_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); memset(&my_addr, 0, sizeof(struct sockaddr_ll)); my_addr.sll_family = PF_PACKET; my_addr.sll_protocol = htons(ETH_P_ALL); strcpy(str_devname, "eth0"); strncpy(s_ifr.ifr_name, str_devname, sizeof(s_ifr.ifr_name)); ec = ioctl(fd_socket, SIOCGIFINDEX, &s_ifr); i_ifindex = s_ifr.ifr_ifindex; memset(&my_addr, 0, sizeof(struct sockaddr_ll)); my_addr.sll_family = AF_PACKET; my_addr.sll_protocol = ETH_P_ALL; my_addr.sll_ifindex = i_ifindex; bind(fd_socket, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_ll) s_packet_req.tp_block_size = c_buffer_sz; s_packet_req.tp_frame_size = c_buffer_sz; s_packet_req.tp_block_nr = c_buffer_nb; s_packet_req.tp_frame_nr = c_buffer_nb; size = s_packet_req.tp_block_size * s_packet_req.tp_block_nr; if (setsockopt(fd_socket, SOL_PACKET, PACKET_TX_RING, (char *) &s_packet_req, sizeof(s_packet_req)) < 0) { perror("setsockopt: PACKET_TX_RING"); return; } if (c_sndbuf_sz) { printf("send buff size = %d\n", c_sndbuf_sz); if (setsockopt(fd_socket, SOL_SOCKET, SO_SNDBUF, &c_sndbuf_sz, sizeof(c_sndbuf_sz)) < 0){ perror("getsockopt: SO_SNDBUF"); exit(1); } } data_offset = TPACKET_HDRLEN - sizeof(struct sockaddr_ll); printf("data offset = %d bytes\n", data_offset); ps_header_start = (tpacket_hdr *) mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_socket, 0); if (ps_header_start == (void*) -1) { perror("mmap"); exit(1); } Then I fill data ps_header = ((struct tpacket_hdr *) ((char *) ps_header_start + (c_buffer_sz * i_index))); if (!ps_header) { perror("ps_header") ; return NULL; } data = ((char*) ps_header) + data_offset; switch ((volatile uint32_t) ps_header->tp_status) { case TP_STATUS_AVAILABLE: printf("TP_STATUS_AVAILABLE, index=%d\n",i_index) ; memcpy(data, packet_data, size); pthread_mutex_lock(&index_locker) ; i_index++; pthread_mutex_unlock(&index_locker) ; if (i_index >= c_buffer_nb) { i_index = 0; first_loop = 0; } /* update packet len */ ps_header->tp_len = size; /* set header flag to USER (trigs xmit)*/ ps_header->tp_status = TP_STATUS_SEND_REQUEST; then I send ec_send = sendto(fd_socket, NULL, 0, 0, (struct sockaddr *) ps_sockaddr, sizeof(struct sockaddr_ll)); I have got no errors, ec_send=not null size of sended data. But there are no data routed to destination host. So, I ask - what data I should pass to ring buffer, now I include headers ip,tcp, should I include MAC header? - May be I have to set additional flags to route my packets.

    Read the article

  • Receiving Multicast Messages on a Multihomed Windows PC

    - by Basti
    I'm developing a diagnostic tool on a PC with several Network Interfaces based on multicast/udp. The user can select a NIC, the application creates sockets, binds them to this NIC and adds them to the specific multicast group. The sending of multicast messages works fine. However receiving of messages only succeeds if I bind the sockets to a specific NIC of my PC. It almost looks like as there is a 'default' NIC for receiving multicast messages in Windows which is always the first NIC returned by the GetAdapterInfo function. I monitored the network with Wireshark and discovered that the "IGMP Join Group" message isn't sent from the NIC I bound the socket at, but by this 'default' NIC. If I disable this NIC (or remove the network cable), the next NIC of the list returned by GetAdapterInfo is used for receiving multicast messages. I was successful to change this 'default' NIC by adding an additional entry to the routing table of my PC, but I don't think this is a good solution of the problem. The problem also occurs with the code appended below. The join group messages isn't sent via 192.168.52 but via a different NIC. // socket_tst.cpp : Defines the entry point for the console application. // #include tchar.h #include winsock2.h #include ws2ipdef.h #include IpHlpApi.h #include IpTypes.h #include stdio.h int _tmain(int argc, _TCHAR* argv[]) { WSADATA m_wsaData; SOCKET m_socket; sockaddr_in m_sockAdr; UINT16 m_port = 319; u_long m_interfaceAdr = inet_addr("192.168.1.52"); u_long m_multicastAdr = inet_addr("224.0.0.107"); int returnValue = WSAStartup(MAKEWORD(2,2), &m_wsaData); if (returnValue != S_OK) { return returnValue; } // Create sockets if (INVALID_SOCKET == (m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) ) { return WSAGetLastError(); } int doreuseaddress = TRUE; if (setsockopt(m_socket,SOL_SOCKET,SO_REUSEADDR,(char*) &doreuseaddress,sizeof(doreuseaddress)) == SOCKET_ERROR) { return WSAGetLastError(); } // Configure socket addresses memset(&m_sockAdr,0,sizeof(m_sockAdr)); m_sockAdr.sin_family = AF_INET; m_sockAdr.sin_port = htons(m_port); m_sockAdr.sin_addr.s_addr = m_interfaceAdr; //bind sockets if ( bind( m_socket, (SOCKADDR*) &m_sockAdr, sizeof(m_sockAdr) ) == SOCKET_ERROR ) { return WSAGetLastError(); } // join multicast struct ip_mreq_source imr; memset(&imr,0,sizeof(imr)); imr.imr_multiaddr.s_addr = m_multicastAdr; // address of multicastgroup imr.imr_sourceaddr.s_addr = 0; // sourceaddress (not used) imr.imr_interface.s_addr = m_interfaceAdr; // interface address /* first join multicast group, then registerer selected interface as * multicast sending interface */ if( setsockopt( m_socket ,IPPROTO_IP ,IP_ADD_MEMBERSHIP ,(char*) &imr , sizeof(imr)) == SOCKET_ERROR) { return SOCKET_ERROR; } else { if( setsockopt(m_socket ,IPPROTO_IP ,IP_MULTICAST_IF ,(CHAR*)&imr.imr_interface.s_addr ,sizeof(&imr.imr_interface.s_addr)) == SOCKET_ERROR ) { return SOCKET_ERROR; } } printf("receiving msgs...\n"); while(1) { // get inputbuffer from socket int sock_return = SOCKET_ERROR; sockaddr_in socketAddress; char buffer[1500]; int addressLength = sizeof(socketAddress); sock_return = recvfrom(m_socket, (char*) &buffer, 1500, 0, (SOCKADDR*)&socketAddress, &addressLength ); if( sock_return == SOCKET_ERROR) { int wsa_error = WSAGetLastError(); return wsa_error; } else { printf("got message!\n"); } } return 0; } Thanks four your help!

    Read the article

  • Spikes in Socket Performance

    - by Harun Prasad
    We are facing random spikes in high throughput transaction processing system using sockets for IPC. Below is the setup used for the run: The client opens and closes new connection for every transaction, and there are 4 exchanges between the server and the client. We have disabled the TIME_WAIT, by setting the socket linger (SO_LINGER) option via getsockopt as we thought that the spikes were caused due to the sockets waiting in TIME_WAIT. There is no processing done for the transaction. Only messages are passed. OS used Centos 5.4 The average round trip time is around 3 milli seconds, but some times the round trip time ranges from 100 milli seconds to couple of seconds. Steps used for Execution and Measurement and output Starting the server $ python sockServerLinger.py /dev/null & Starting the client to post 1 million transactions to the server. And logs the time for a transaction in the client.log file. $ python sockClient.py 1000000 client.log Once the execution finishes the following command will show the execution time greater than 100 milliseconds in the format <line_number>:<execution_time>. $ grep -n "0.[1-9]" client.log | less Below is the example code for Server and Client. Server # File: sockServerLinger.py import socket, traceback,time import struct host = '' port = 9999 l_onoff = 1 l_linger = 0 lingeropt = struct.pack('ii', l_onoff, l_linger) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, lingeropt) s.bind((host, port)) s.listen(1) while 1: try: clientsock, clientaddr = s.accept() print "Got connection from", clientsock.getpeername() data = clientsock.recv(1024*1024*10) #print "asdasd",data numsent=clientsock.send(data) data1 = clientsock.recv(1024*1024*10) numsent=clientsock.send(data) ret = 1 while(ret>0): data1 = clientsock.recv(1024*1024*10) ret = len(data) clientsock.close() except KeyboardInterrupt: raise except: print traceback.print_exc() continue Client # File: sockClient.py import socket, traceback,sys import time i = 0 while 1: try: st = time.time() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) while (s.connect_ex(('127.0.0.1',9999)) != 0): continue numsent=s.send("asd"*1000) response = s.recv(6000) numsent=s.send("asd"*1000) response = s.recv(6000) i+=1 if i == int(sys.argv[1]): break except KeyboardInterrupt: raise except: print "in exec:::::::::::::",traceback.print_exc() continue print time.time() -st

    Read the article

  • UDP sockets in ad hoc network (Ubuntu 9.10)

    - by Ekhiotz
    Hi! I am using BSD sockets in Ubuntu 9.10 to send UDP packets in broadcast with the following code: sock_fd = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP); //sock_fd=socket(AF_INET,SOCK_DGRAM,0); receiver_addr.sin_family = PF_INET; //does not send with broadcast in ad hoc receiver_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST); inet_aton("169.254.255.255",&receiver_addr.sin_addr); receiver_addr.sin_port = htons(port); int broadcast = 1; // this call is what allows broadcast packets to be sent: if (setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) == -1) { perror("setsockopt (SO_BROADCAST)"); exit(1); } ret=sendto(sock_fd, packet, size, 0,(struct sockaddr*)&receiver_addr,sizeof(receiver_addr)); Note that is not all the code, it is only to have an idea. The program sends all the data with INADDR_BROADCAST if I am connected to an infrastructure wireless network. However, if my laptop is connected to an ad-hoc network, it is able to receive all the data, but not to send it. I have solved the problem using the 169.254.255.255 broadcast address, but I would like to know what is going on. Thank you in advance!

    Read the article

  • Why is a non-blocking TCP connect() occasionally so slow on Linux?

    - by pts
    I was trying to measure the speed of a TCP server I'm writing, and I've noticed that there might be a fundamental problem of measuring the speed of the connect() calls: if I connect in a non-blocking way, connect() operations become very slow after a few seconds. Here is the example code in Python: #! /usr/bin/python2.4 import errno import os import select import socket import sys def NonBlockingConnect(sock, addr): while True: try: return sock.connect(addr) except socket.error, e: if e.args[0] not in (errno.EINPROGRESS, errno.EALREADY): raise os.write(2, '^') if not select.select((), (sock,), (), 0.5)[1]: os.write(2, 'P') def InfiniteClient(addr): while True: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setblocking(0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # sock.connect(addr) NonBlockingConnect(sock, addr) sock.close() os.write(2, '.') def InfiniteServer(server_socket): while True: sock, addr = server_socket.accept() sock.close() server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('127.0.0.1', 45454)) server_socket.listen(128) if os.fork(): # Parent. InfiniteServer(server_socket) else: addr = server_socket.getsockname() server_socket.close() InfiniteClient(addr) With NonBlockingConnect, most connect() operations are fast, but in every few seconds there happens to be one connect() operation which takes at least 2 seconds (as indicated by 5 consecutive P letters on the output). By using sock.connect instead of NonBlockingConnect all connect operations seem to be fast. How is it possible to get rid of these slow connect()s? I'm running Ubuntu Karmic desktop with the standard PAE kernel: Linux narancs 2.6.31-20-generic-pae #57-Ubuntu SMP Mon Feb 8 10:23:59 UTC 2010 i686 GNU/Linux

    Read the article

1 2 3  | Next Page >