working on it ...

Filters

Explore Public Snippets

Sort by

Found 408 snippets matching: udp

    public by tomsim  2436  16  5  0

    Send UDP WOL Magic Package

    C program to send UDP magic package to wake on lan
    /* Compile on Windows:
    cl /nologo /W3 /O2 /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_X86_" /link wsock32.lib wol.c
    Compile on linux:
    gcc wol.c -o wol
    
    Change the subnet on line 161 to match your network (sorry!)
    Must configure nic to accept magic package and setup power profile to allow
    wake on lan from nic.  Not for WiFi.
    */
    #ifdef _WIN32
    #define WIN32_LEAN_AND_MEAN
    #include <winsock2.h>
    #else
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    #endif
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <stdarg.h>
    #include <string.h>
    
    #ifdef _WIN32
    #define ERR_RETURN( x, e) if (x == SOCKET_ERROR) { checkError( e); return(0); }
    #else
    #define ERR_RETURN( x, e) if (x < 0) { checkError( e); return(0); }
    #define SOCKET int
    #endif
    
    static int checkError( char *szMsg)
    {
    #ifdef _WIN32
    	int err = WSAGetLastError();
    	if ((err == WSAEINTR) || (err == WSAEWOULDBLOCK) || (err == WSAEINPROGRESS))
    	{
    		printf( "Warning error=%08.8x\n", errno);
    		return 1;
    	}
    	else
    	{
    		printf("Error %d: %s\n", err, szMsg);
    		WSACleanup();
    		return 0;
    	}
    #else
    	perror(szMsg);
    	if ((errno == EINTR) || (errno = EWOULDBLOCK) || (errno == EINPROGRESS))
    		return 1;
    	else
    		return 0;
    #endif
    }
    #ifdef _WIN32
    /*--------------------------------------------------------
      Window socket startup
      --------------------------------------------------------*/
    int socketStartWin32(void)
    {
    	WSADATA wsaData;
    	if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR)
    	{
    		printf("WSAStartup failed with error %d\n",WSAGetLastError());
    		WSACleanup();
    		return -1;
    	}
    	return 0;
    }
    void socketEndWin32(void)
    {
       WSACleanup();
    }
    #endif
    
    /* Magic package format:
    	06 x 255 or (0xff)
    	16 x MAC Address of target PC
    
    */ 
    int main(int argc, char **argv)
    {
    	int i;
    	unsigned char tosend[102];
    	unsigned char mac[6];
    
    	if ((argc < 2) || (strlen(argv[1]) < 17))
    	{
    		printf("Usage wol <mac address aa:bb:cc:dd:ee:ff>\n");
    		exit(0);
    	}
    
    	/** store mac address **/
    	for (i=0; i < sizeof(mac); i++)
    	{
    		char *cp = &argv[1][i*3];
    		mac[i] = 0x00;
    		sscanf(cp,"%2X", (unsigned int *) &mac[i]);
    	}
    	if (argc > 2)	// validate before sent
    	{
    		int ecn = 0;
    		printf( "Send magic package to ");
    		for (i=0; i < sizeof(mac); i++)
    		{
    			if (i) printf(":");
    			printf( "%.2X", mac[i]);
    			if (!mac[i]) ecn++;
    		}
    		printf("\n");
    		if (ecn)
    		{
    			printf("Invalid mac address\n");
    			exit(0);
    		}
    	}
    
    
    	/** first 6 bytes of 255 **/
    	for( i = 0; i < 6; i++) {
    		tosend[i] = 0xFF;
    	}
    	/** append it 16 times to packet **/
    	for( i = 1; i <= 16; i++)
    	{
    		memcpy(&tosend[i * 6], mac, 6 * sizeof(unsigned char));
    	}
    
    #ifdef _WIN32
    	if (socketStartWin32())
    		exit(-1);
    #endif
    	if (1)
    	{
    		int udpSocket;
    		struct sockaddr_in udpClient, udpServer;
    		int broadcast = 1;
    		int rv;
    
    		udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
    
    		/** you need to set this so you can broadcast **/
    		if (setsockopt(udpSocket, SOL_SOCKET, SO_BROADCAST, (char *) &broadcast, sizeof broadcast))
    		{
    			checkError("setsockopt (SO_BROADCAST)");
    			exit(1);
    		}
    		udpClient.sin_family = AF_INET;
    		udpClient.sin_addr.s_addr = INADDR_ANY;
    		udpClient.sin_port = 0;
    
    		bind(udpSocket, (struct sockaddr*)&udpClient, sizeof(udpClient));
    
    		/** …make the packet as shown above **/
    
    		/** set server end point (the broadcast addres)**/
    		udpServer.sin_family = AF_INET;
    		udpServer.sin_addr.s_addr = inet_addr("192.168.1.255");
    		udpServer.sin_port = htons(9);
    
    		/** send the packet **/
    		rv = sendto(udpSocket, tosend, sizeof(unsigned char) * sizeof(tosend), 0, (struct sockaddr*)&udpServer, sizeof(udpServer));
    		if (argc > 2) printf( "Sent %d bytes\n", rv);
    	}
    
    #ifdef _WIN32
    	socketEndWin32();
    #endif
    	return 0;
    }
    
                                        

    public by fukusuke1026  1309  0  3  0

    Ruby:UDPクライアント

    Ruby:UDPクライアント: gistfile1.rb
    #!/usr/bin/ruby
    
    require "socket"
    
    udp = UDPSocket.open()
    
    sockaddr = Socket.pack_sockaddr_in(514, "172.28.202.40")
    
    num = 0
    while num < 10 do
    	in_f = open("500.log","r")
    	sent = 0
    	for sendlog in in_f
    		udp.send(sendlog, 0, sockaddr)
    		sent = sent + 1
    		if sent >= 50 then
    			break
    		end
    	end
    	print num,":",sent,"\n"
    	in_f.close
    	sleep 1
    	num = num + 1
    end
    
    udp.close
    
    
    

    external by makcuk  386882  92  3  0

    A simple python tun/tap udp tunnel example

    A simple python tun/tap udp tunnel example: tap-linux.py
    # Simple linux tun/tap device example tunnel over udp
    # create tap device with ip tuntap add device0 tap
    # set ip address on it and run tap-linux on that device and set desitation ip
    # run same on another node, changing dst ip to first node
    
    import fcntl
    import struct
    import os
    import socket
    import threading
    import sys
    
    TUNSETIFF = 0x400454ca
    TUNSETOWNER = TUNSETIFF + 2
    IFF_TUN = 0x0001
    IFF_TAP = 0x0002
    IFF_NO_PI = 0x1000
    
    
    def udp_send(dst, packet):
        print "udp_send"
        sock.sendto(packet, (dst, 40000))
    
    def recv():
         ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
         ss.bind(("0.0.0.0", 40000))
         while True:
             data, addr = ss.recvfrom(1024)
             print "udp_recv"
             os.write(tun.fileno(), data)
    
    if __name__ == "__main__":
    
        if len(sys.argv) < 3:
            print "Usage: tap-linux.py <tap_interface> <dst_address_of_tunnel>"
            sys.exit(1)
        iface = sys.argv[1]
        dst = sys.argv[2]
        print "Working on %s inteface, destination address %s:40000 udp" % (iface, dst)
        tun = open('/dev/net/tun', 'r+b')
        ifr = struct.pack('16sH', iface, IFF_TAP | IFF_NO_PI)
        fcntl.ioctl(tun, TUNSETIFF, ifr)
        fcntl.ioctl(tun, TUNSETOWNER, 1000)
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
        t = threading.Thread(target=recv)
        try:
            t.start()
            while True:
                packet = os.read(tun.fileno(), 2048)
                if True:
                    udp_send(dst, packet)
    
        except KeyboardInterrupt:
            print "Terminating ..."
            os._exit(0)
    
    

    external by cesar-carrasco  137521  2  4  0

    log4net UDP Appender to send signals to Graphite server

    log4net UDP Appender to send signals to Graphite server: log4net.config.xml
    XML
      <appender name="GraphiteUdpAppender" type="log4net.Appender.UdpAppender">
        <remoteAddress value="graphiteserver.somewhere.com"/>
        <remotePort value="8125"/>
        <layout type="log4net.Layout.PatternLayout">
          <IgnoresException value="False"/>
          <conversionPattern value="%property{log4net:HostName}.log4net.%level:1|kv\n"/>
        </layout>
      </appender>
      
      <!-- Remember to add the appender to the root
        <root>
    	...
        <appender-ref ref="GraphiteUdpAppender" />
      </root>
      -->
      
    
    

    external by Sergei Nikulov  205  0  2  0

    Linux UDP tunning

    Linux UDP tunning: gistfile1.txt
       33  sudo sysctl -w net.ipv4.udp_rmem_min=131072
       35  sudo sysctl -w net.ipv4.udp_wmem_min=131072
       37  sudo sysctl -w net.core.rmem_max=67108864
       39  sudo sysctl -w net.ipv4.udp_mem='262144 327680 393216'
    
    
    >>>>>>>>>>> old values <<<<<<<<<<<<<<<<<<<
    diode@tx:~$ sudo sysctl net |grep mem
    [sudo] password for diode: 
    net.core.wmem_max = 2097152
    net.core.rmem_max = 2097152
    net.core.wmem_default = 2097152
    net.core.rmem_default = 2097152
    net.core.optmem_max = 20480
    net.ipv4.igmp_max_memberships = 20
    net.ipv4.tcp_mem = 96168        128224  192336
    net.ipv4.tcp_wmem = 4096        16384   4103168
    net.ipv4.tcp_rmem = 4096        87380   4103168
    net.ipv4.udp_mem = 96168        128224  192336
    net.ipv4.udp_rmem_min = 4096
    net.ipv4.udp_wmem_min = 4096
    
    
    
    

    external by sergey08  380  0  3  0

    Connect to AppLamp / Mi Light Wifi Box over UDP and send HEX commands (UDP multicast supported: IP ending on .255)

    Connect to AppLamp / Mi Light Wifi Box over UDP and send HEX commands (UDP multicast supported: IP ending on .255): wifibox.js
    /**
     Filename: wifibox.js
     //AppLamp.nl Wifi LED light API: wifi box UDP socket, command sender
     © AppLamp.nl: you can share,modify and use this code (commercially) as long as you
     keep the referer "AppLamp.nl led light API" in the file header.
    
    
     Usage in Node JS:
         //load this wifi box class
         var WifiBoxModule = require('wifibox.js');
         var cmd = require('commands.js');
         //create instance with wifi box ip and port
         var box = new WifiBoxModule("192.168.1.255", 8899);
         //send a command ( see commands.js )
         box.command(cmd.rgbw.hue(180));
         box.command(cmd.white.allOn());
         
         
         TIP: You don't need to know the exact IP of your Wifi Box. 
              If you know your DHCP IP range, just replace the last digit to .255 
              That way you wil perform a UDP multicast and the wifi box will receive it. 
              So for example your network range is 192.168.1.1  to 192.18.1.254,
              then use 192.18.1.255 to perform a multicast.
     **/
    
    var http = require('http');
    var dgram = require('dgram');
    
    var WifiBox = function (ip, port) {
        this.client = dgram.createSocket('udp4');
        const default_ip = '192.168.1.255';
        const default_port = 8899;
        this.ip = (ip != undefined && ip.length > 6) ? ip : default_ip;
        this.port = (port != undefined && port > 0) ? port : default_port;
    
    };
    
    
    WifiBox.prototype.command = function (threeByteArray) {
        var buffer = new Buffer(threeByteArray);
        this.client.send(buffer
            , 0
            , buffer.length
            , this.port
            , this.ip
            , function (err, bytes) {
                if (err) {
                    console.log("udp error:" + err);
                    throw err;
                } else {
                    console.log('bytes send: ' + [threeByteArray[0], threeByteArray[1], threeByteArray[2]])
                }
            }
        );
    }
    
    WifiBox.prototype.toString = function () {
        return 'WifiBox: { ip:' + this.ip + ':' + this.port + '}';
    };
    
    
    module.exports = WifiBox;
    
    

    external by thisismyrobot  244  0  3  0

    Configuring SocketServer.UDPServer to receive Parrot Jumping Sumo UDP video packets

    Configuring SocketServer.UDPServer to receive Parrot Jumping Sumo UDP video packets: socketserver_example.py
    import SocketServer
    
    if __name__ == '__main__':
        server = SocketServer.UDPServer((HOST, PORT), UDPHandler)
        server.max_packet_size = 65000
    
    
    

    external by Malcolm Ke Win  32  0  1  0

    udp over kcptun(tcp over udp)

    udp over kcptun(tcp over udp): udp over kcptun(tcp over udp)
    kcptun是tcp over udp没做udp over udp,可用socat搞定:
    Client side:
    socat -T15 udp4-recvfrom:53,reuseaddr,fork tcp:localhost:10053
    kcptun_client_linux -r "vps_ip:60053" -l ":10053" -mode fast2 -key "fuck ccp fuck ccp"
    
    Server side:
    kcptun_server_linux -t "127.0.0.1:10053" -l ":60053" -mode fast2 -key "fuck ccp fuck ccp"
    socat tcp4-listen:10053,reuseaddr,fork udp:8.8.8.8:53
    
    因为google dns支持tcp, 服务端可以省一步:
    Server side:
    kcptun_server_linux -t "8.8.8.8:53" -l ":60053" -mode fast2 -key "fuck ccp fuck ccp"
    
    更简化, 其实只要用kcptun打通22端口比如监听在60022,
    然后ssh -L 10053:8.8.8.8:53 user@127.0.0.1 -p 60022,
    然后本地用unbound(linux)或dnslite(android)来把10053上的tcp dns转成udp dns查询就行了
    
    
    

    external by amidvidy  148  0  2  0

    UDP name server

    UDP name server: gistfile1.cpp
    C++
    #include <string>
    #include <iostream>
    #include <boost/asio.hpp>
    #include <boost/algorithm/string.hpp>
    #include <boost/bind.hpp>
    
    using boost::asio::ip::udp;
    
    namespace {
    
    class HelloWorldServer {
    public:
        HelloWorldServer(boost::asio::io_service& io_service)
            : _socket(io_service, udp::endpoint(udp::v4(), 1111))
        {
            startReceive();
        }
    private:
        void startReceive() {
            _socket.async_receive_from(
                boost::asio::buffer(_recvBuffer), _remoteEndpoint,
                boost::bind(&HelloWorldServer::sendWelcome, this,
                    boost::asio::placeholders::error,
                            boost::asio::placeholders::bytes_transferred));
        }
    
        void sendWelcome(const boost::system::error_code& error,
                         std::size_t bytes_transferred) {
            std::string message{"Welcome. What is your name?\n"};
            _socket.async_send_to(boost::asio::buffer(message), _remoteEndpoint,
                                  boost::bind(&HelloWorldServer::getName, this,
                                              boost::asio::placeholders::error,
                                              boost::asio::placeholders::bytes_transferred));
        }
    
        void getName(const boost::system::error_code& error,
                     std::size_t bytes_transferred) {
            if (!error || error == boost::asio::error::message_size) {
                _socket.async_receive_from(boost::asio::buffer(_recvBuffer), _remoteEndpoint,
                                           boost::bind(&HelloWorldServer::sendHello, this,
                                                       boost::asio::placeholders::error,
                                                       boost::asio::placeholders::bytes_transferred));
            }
        }
    
        void sendHello(const boost::system::error_code& error,
                       std::size_t bytes_transferred) {
            if (!error || error == boost::asio::error::message_size) {
                std::string name{_recvBuffer.data(), bytes_transferred};
                boost::algorithm::trim(name);
                auto message = "Hello, " + name + "\n";
                _socket.async_send_to(boost::asio::buffer(message), _remoteEndpoint,
                                      boost::bind(&HelloWorldServer::handleSend, this,
                                                  boost::asio::placeholders::error,
                                                  boost::asio::placeholders::bytes_transferred));
            }
        }
    
        void handleSend(const boost::system::error_code& ec,
                        std::size_t bytes_transferred) {
            
            startReceive();
        }
    
        udp::socket _socket;
        udp::endpoint _remoteEndpoint;
        std::array<char, 1024> _recvBuffer;
    };
    
    }  // namespace
    
    int main() {
        try {
            boost::asio::io_service io_service;
            HelloWorldServer server{io_service};
            io_service.run();
        } catch (const std::exception& ex) {
            std::cerr << ex.what() << std::endl;
        }
        return 0;
    }
    
    
    

    external by Lu Guanqun  137  0  2  0

    manipulate pcap with tshark: dump its udp port

    manipulate pcap with tshark: dump its udp port: tshark.sh
    /usr/bin/tshark -r some.cap.gz -T fields -e ip.dst -e udp.port -R "udp" > output.txt
    
    
    • Public Snippets
    • Channels Snippets