Rectangle 27 1

It's a good thing Eclipse's history works even for a day back :) Thanks to that, I am able to give both Ravi a working example and Lirik his answer on leakage.

Let me first start of by stating that I have no clue what is causing this leak, but if I leave it long enough, it will fail on a OutOfMemoryError.

Second, I left the working code commented out for Ravi for a working basic example of my UDP server. The timeout was there to test how long my firewall would kill the receivers end (30 seconds). Just remove anything with the pool, and you're good to go.

So here is, a working but leaking version of my example threaded UDP server.

public class TestServer {

private static Integer TIMEOUT = 30;
private final static int MAX_BUFFER_SIZE = 8192;
private final static int MAX_LISTENER_THREADS = 5;
private final static SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss.SSSZ");

private int mPort;
private DatagramSocket mSocket;

// You can remove this for a working version
private ExecutorService mPool;

public TestServer(int port) {
    mPort = port;
    try {
        mSocket = new DatagramSocket(mPort);
        mSocket.setReceiveBufferSize(MAX_BUFFER_SIZE);
        mSocket.setSendBufferSize(MAX_BUFFER_SIZE);
        mSocket.setSoTimeout(0);

        // You can uncomment this for a working version
        //for (int i = 0; i < MAX_LISTENER_THREADS; i++) {
        //  new Thread(new Listener(mSocket)).start();
        //}

        // You can remove this for a working version
        mPool = Executors.newFixedThreadPool(MAX_LISTENER_THREADS);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

// You can remove this for a working version
public void start() {
    try {
        try {
            while (true) {
                mPool.execute(new Listener(mSocket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } finally {
        mPool.shutdown();
    }
}

private class Listener implements Runnable {

    private final DatagramSocket socket;

    public Listener(DatagramSocket serverSocket) {
        socket = serverSocket;
    }

    private String readLn(DatagramPacket packet) throws IOException {
        socket.receive(packet);
        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(packet.getData())), MAX_BUFFER_SIZE).readLine();
    }

    private void writeLn(DatagramPacket packet, String string) throws IOException {
        packet.setData(string.concat("\r\n").getBytes());
        socket.send(packet);
    }

    @Override
    public void run() {
        DatagramPacket packet = new DatagramPacket(new byte[MAX_BUFFER_SIZE], MAX_BUFFER_SIZE);
        String s;
        while (true) {
            try {
                packet = new DatagramPacket(new byte[MAX_BUFFER_SIZE], MAX_BUFFER_SIZE);
                s = readLn(packet);
                System.out.println(DateFormat.format(new Date()) + " Received: " + s);
                Thread.sleep(TIMEOUT * 1000);
                writeLn(packet, s);
                System.out.println(DateFormat.format(new Date()) + " Sent: " + s);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[] args) {
    if (args.length == 1) {
        try {
            TIMEOUT = Integer.parseInt(args[0]);
        } catch (Exception e) {
            TIMEOUT = 30;
        }
    }
    System.out.println(DateFormat.format(new Date()) + " Timeout: " + TIMEOUT);
    //new TestServer(4444);
    new TestServer(4444).start();
}
}

btw. @Lirik, I witnessed this behavior first in Eclipse, after which I tested it from the command line. And again, I have NO clue what is causing it ;) sorry...

Java: Multithreading & UDP Socket Programming - Stack Overflow

java multithreading sockets udp
Rectangle 27 2

I have the same problem, udp socket does not receive scapy packet. I suppose there might be something related to this post: Raw Socket Help: Why UDP packets created by raw sockets are not being received by kernel UDP? And what works for me is the socket.IP_HDRINCL option. Here is the working code for both and sender.

import socket
from scapy.all import *

rawudp=socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
rawudp.bind(('0.0.0.0',56789))
rawudp.setsockopt(socket.SOL_IP, socket.IP_HDRINCL,1)

pkt = IP()/UDP(sport=56789, dport=7890)/'hello'

rawudp.sendto(pkt.build(), ('127.0.0.1',7890))
import socket
so = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
so.bind(('0.0.0.0',7890))
while True:
    print so.recv(1024)

Talking to C socket with Scapy - Stack Overflow

c sockets networking scapy localserversocket
Rectangle 27 8

// Client form:
// In this case, we're connecting to a specific server, so the client will
// usually use:
//       Connect(address)    // Connect to a UDP server
//       Read/Write          // Reads/Writes all go to a single destination
//
// Server form:
// In this case, we want to read/write to many clients which are connecting
// to this server.  First the server 'binds' to an addres, then we read from
// clients and write responses to them.
// Example:
//       Bind(address/port)  // Binds to port for reading from clients
//       RecvFrom/SendTo     // Each read can come from a different client
//                           // Writes need to be directed to a specific
//                           // address.
chrome.socket.bind
chrome.socket.recvFrom
chrome.socket.sendTo
chrome.socket.connect
chrome.socket.read
chrome.socket.write
var serverSocket;
var clientSocket;

// From https://developer.chrome.com/trunk/apps/app_hardware.html
var str2ab=function(str) {
  var buf=new ArrayBuffer(str.length);
  var bufView=new Uint8Array(buf);
  for (var i=0; i<str.length; i++) {
    bufView[i]=str.charCodeAt(i);
  }
  return buf;
}

// From https://developer.chrome.com/trunk/apps/app_hardware.html
var ab2str=function(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
};

// Server
chrome.socket.create('udp', null, function(createInfo){
    serverSocket = createInfo.socketId;

    chrome.socket.bind(serverSocket, '127.0.0.1', 1345, function(result){
        console.log('chrome.socket.bind: result = ' + result.toString());
    });

    function read()
    {
        chrome.socket.recvFrom(serverSocket, 1024, function(recvFromInfo){
            console.log('Server: recvFromInfo: ', recvFromInfo, 'Message: ', 
                ab2str(recvFromInfo.data));
            if(recvFromInfo.resultCode >= 0)
            {
                chrome.socket.sendTo(serverSocket, 
                    str2ab('Received message from client ' + recvFromInfo.address + 
                    ':' + recvFromInfo.port.toString() + ': ' + 
                    ab2str(recvFromInfo.data)), 
                    recvFromInfo.address, recvFromInfo.port, function(){});
                read();
            }
            else
                console.error('Server read error!');
        });
    }

    read();
});

// A client
chrome.socket.create('udp', null, function(createInfo){
    clientSocket = createInfo.socketId;

    chrome.socket.connect(clientSocket, '127.0.0.1', 1345, function(result){
        console.log('chrome.socket.connect: result = ' + result.toString());
    });

    chrome.socket.write(clientSocket, str2ab('Hello server!'), function(writeInfo){
        console.log('writeInfo: ' + writeInfo.bytesWritten + 
            'byte(s) written.');
    });

    chrome.socket.read(clientSocket, 1024, function(readInfo){
        console.log('Client: received response: ' + ab2str(readInfo.data), readInfo);
    });
});

javascript - Chrome packaged app UDP sockets not working - Stack Overf...

javascript sockets google-chrome google-chrome-extension google-chrome-app
Rectangle 27 1

I've got some code snippets that might help you out as I've been working with MPEG-TS also.

Starting with my packet thread which checks each packet against the stream ID's which I've already found and got the codec contexts:

void *FFMPEG::thread_packet_function(void *arg) {
    FFMPEG *ffmpeg = (FFMPEG*)arg;
    for (int c = 0; c < MAX_PACKETS; c++)
        ffmpeg->free_packets[c] = &ffmpeg->packet_list[c];
    ffmpeg->packet_pos = MAX_PACKETS;

    Audio.start_decoding();
    Video.start_decoding();
    Subtitle.start_decoding();

    while (!ffmpeg->thread_quit) {
        if (ffmpeg->packet_pos != 0 &&
                Audio.okay_add_packet() &&
                Video.okay_add_packet() &&
                Subtitle.okay_add_packet()) {

            pthread_mutex_lock(&ffmpeg->packet_mutex); // get free packet
            AVPacket *pkt = ffmpeg->free_packets[--ffmpeg->packet_pos]; // pre decrement
            pthread_mutex_unlock(&ffmpeg->packet_mutex);

            if ((av_read_frame(ffmpeg->fContext, pkt)) >= 0) { // success
                int id = pkt->stream_index;
                if (id == ffmpeg->aud_stream.stream_id) Audio.add_packet(pkt);
                else if (id == ffmpeg->vid_stream.stream_id) Video.add_packet(pkt);
                else if (id == ffmpeg->sub_stream.stream_id) Subtitle.add_packet(pkt);
                else { // unknown packet
                    av_packet_unref(pkt);

                    pthread_mutex_lock(&ffmpeg->packet_mutex); // put packet back
                    ffmpeg->free_packets[ffmpeg->packet_pos++] = pkt;
                    pthread_mutex_unlock(&ffmpeg->packet_mutex);

                    //LOGI("Dumping unknown packet, id %d", id);
                }
            } else {
                av_packet_unref(pkt);

                pthread_mutex_lock(&ffmpeg->packet_mutex); // put packet back
                ffmpeg->free_packets[ffmpeg->packet_pos++] = pkt;
                pthread_mutex_unlock(&ffmpeg->packet_mutex);

                //LOGI("No packet read");
            }
        } else { // buffers full so yield
            //LOGI("Packet reader on hold: Audio-%d, Video-%d, Subtitle-%d",
            //  Audio.packet_pos, Video.packet_pos, Subtitle.packet_pos);
            usleep(1000);
            //sched_yield();
        }
    }
    return 0;
}

Each decoder for audio, video and subtitles have their own threads which receive the packets from the above thread in ring buffers. I've had to separate the decoders into their own threads because CPU usage was increasing when I started using the deinterlace filter.

My video decoder reads the packets from the buffers and when it has finished with the packet sends it back to be unref'd and can be used again. Balancing the packet buffers doesn't take that much time once everything is running.

Here's the snipped from my video decoder:

void *VideoManager::decoder(void *arg) {
    LOGI("Video decoder started");
    VideoManager *mgr = (VideoManager *)arg;
    while (!ffmpeg.thread_quit) {
        pthread_mutex_lock(&mgr->packet_mutex);
        if (mgr->packet_pos != 0) {
            // fetch first packet to decode
            AVPacket *pkt = mgr->packets[0];

            // shift list down one
            for (int c = 1; c < mgr->packet_pos; c++) {
                mgr->packets[c-1] = mgr->packets[c];
            }
            mgr->packet_pos--;
            pthread_mutex_unlock(&mgr->packet_mutex); // finished with packets array

            int got;
            AVFrame *frame = ffmpeg.vid_stream.frame;
            avcodec_decode_video2(ffmpeg.vid_stream.context, frame, &got, pkt);
            ffmpeg.finished_with_packet(pkt);
            if (got) {
#ifdef INTERLACE_ALL
                if (!frame->interlaced_frame) mgr->add_av_frame(frame, 0);
                else {
                    if (!mgr->filter_initialised) mgr->init_filter_graph(frame);
                    av_buffersrc_add_frame_flags(mgr->filter_src_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF);
                    int c = 0;
                    while (true) {
                        AVFrame *filter_frame = ffmpeg.vid_stream.filter_frame;
                        int result = av_buffersink_get_frame(mgr->filter_sink_ctx, filter_frame);
                        if (result == AVERROR(EAGAIN) ||
                                result == AVERROR(AVERROR_EOF) ||
                                result < 0)
                            break;
                        mgr->add_av_frame(filter_frame, c++);
                        av_frame_unref(filter_frame);
                    }
                    //LOGI("Interlaced %d frames, decode %d, playback %d", c, mgr->decode_pos, mgr->playback_pos);
                }
#elif defined(INTERLACE_HALF)
                if (!frame->interlaced_frame) mgr->add_av_frame(frame, 0);
                else {
                    if (!mgr->filter_initialised) mgr->init_filter_graph(frame);
                    av_buffersrc_add_frame_flags(mgr->filter_src_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF);
                    int c = 0;
                    while (true) {
                        AVFrame *filter_frame = ffmpeg.vid_stream.filter_frame;
                        int result = av_buffersink_get_frame(mgr->filter_sink_ctx, filter_frame);
                        if (result == AVERROR(EAGAIN) ||
                                result == AVERROR(AVERROR_EOF) ||
                                result < 0)
                            break;
                        mgr->add_av_frame(filter_frame, c++);
                        av_frame_unref(filter_frame);
                    }
                    //LOGI("Interlaced %d frames, decode %d, playback %d", c, mgr->decode_pos, mgr->playback_pos);
                }
#else
                mgr->add_av_frame(frame, 0);
#endif
            }
            //LOGI("decoded video packet");
        } else {
            pthread_mutex_unlock(&mgr->packet_mutex);
        }
    }
    LOGI("Video decoder ended");
}

As you can see, I'm using a mutex when passing packets back and forth.

Once a frame has been got I just copy the YUV buffers from the frame for later use into another buffer list. I don't convert the YUV, I use a shader which converts the YUV to RGB on the GPU.

void VideoManager::add_av_frame(AVFrame *frame, int field_num) {
    int y_linesize = frame->linesize[0];
    int u_linesize = frame->linesize[1];

    int hgt = frame->height;

    int y_buffsize = y_linesize * hgt;
    int u_buffsize = u_linesize * hgt / 2;

    int buffsize = y_buffsize + u_buffsize + u_buffsize;

    VideoBuffer *buffer = &buffers[decode_pos];

    if (ffmpeg.is_network && playback_pos == decode_pos) { // patched 25/10/16 wlgfx
        buffer->used = false;
        if (!buffer->data) buffer->data = (char*)mem.alloc(buffsize);
        if (!buffer->data) {
            LOGI("Dropped frame, allocation error");
            return;
        }
    } else if (playback_pos == decode_pos) {
        LOGI("Dropped frame, ran out of decoder frame buffers");
        return;
    } else if (!buffer->data) {
        buffer->data = (char*)mem.alloc(buffsize);
        if (!buffer->data) {
            LOGI("Dropped frame, allocation error.");
            return;
        }
    }

    buffer->y_frame = buffer->data;
    buffer->u_frame = buffer->y_frame + y_buffsize;
    buffer->v_frame = buffer->y_frame + y_buffsize + u_buffsize;

    buffer->wid = frame->width;
    buffer->hgt = hgt;

    buffer->y_linesize = y_linesize;
    buffer->u_linesize = u_linesize;

    int64_t pts = av_frame_get_best_effort_timestamp(frame);
    buffer->pts = pts;
    buffer->buffer_size = buffsize;

    double field_add = av_q2d(ffmpeg.vid_stream.context->time_base) * field_num;
    buffer->frame_time = av_q2d(ts_stream) * pts + field_add;

    memcpy(buffer->y_frame, frame->data[0], (size_t) (buffer->y_linesize * buffer->hgt));
    memcpy(buffer->u_frame, frame->data[1], (size_t) (buffer->u_linesize * buffer->hgt / 2));
    memcpy(buffer->v_frame, frame->data[2], (size_t) (buffer->u_linesize * buffer->hgt / 2));

    buffer->used = true;
    decode_pos = (++decode_pos) % MAX_VID_BUFFERS;

    //if (field_num == 0) LOGI("Video %.2f, %d - %d",
    //        buffer->frame_time - Audio.pts_start_time, decode_pos, playback_pos);
}

If there's anything else that I may be able to help with just give me a shout. :-)

The snippet how I open my video stream context which automatically determines the codec, whether it is h264, mpeg2, or another:

void FFMPEG::open_video_stream() {
    vid_stream.stream_id = av_find_best_stream(fContext, AVMEDIA_TYPE_VIDEO,
                                                -1, -1, &vid_stream.codec, 0);
    if (vid_stream.stream_id == -1) return;

    vid_stream.context = fContext->streams[vid_stream.stream_id]->codec;

    if (!vid_stream.codec || avcodec_open2(vid_stream.context,
            vid_stream.codec, NULL) < 0) {
        vid_stream.stream_id = -1;
        return;
    }

    vid_stream.frame = av_frame_alloc();
    vid_stream.filter_frame = av_frame_alloc();
}

This is how I've opened the input stream, whether it be file or URL. The AVFormatContext is the main context for the stream.

bool FFMPEG::start_stream(char *url_, float xtrim, float ytrim, int gain) {
    aud_stream.stream_id = -1;
    vid_stream.stream_id = -1;
    sub_stream.stream_id = -1;

    this->url = url_;
    this->xtrim = xtrim;
    this->ytrim = ytrim;
    Audio.volume = gain;

    Audio.init();
    Video.init();

    fContext = avformat_alloc_context();

    if ((avformat_open_input(&fContext, url_, NULL, NULL)) != 0) {
        stop_stream();
        return false;
    }

    if ((avformat_find_stream_info(fContext, NULL)) < 0) {
        stop_stream();
        return false;
    }

    // network stream will overwrite packets if buffer is full

    is_network =  url.substr(0, 4) == "udp:" ||
                  url.substr(0, 4) == "rtp:" ||
                  url.substr(0, 5) == "rtsp:" ||
                  url.substr(0, 5) == "http:";  // added for wifi broadcasting ability

    // determine if stream is audio only

    is_mp3 = url.substr(url.size() - 4) == ".mp3";

    LOGI("Stream: %s", url_);

    if (!open_audio_stream()) {
        stop_stream();
        return false;
    }

    if (is_mp3) {
        vid_stream.stream_id = -1;
        sub_stream.stream_id = -1;
    } else {
        open_video_stream();
        open_subtitle_stream();

        if (vid_stream.stream_id == -1) { // switch to audio only
            close_subtitle_stream();
            is_mp3 = true;
        }
    }

    LOGI("Audio: %d, Video: %d, Subtitle: %d",
            aud_stream.stream_id,
            vid_stream.stream_id,
            sub_stream.stream_id);

    if (aud_stream.stream_id != -1) {
        LOGD("Audio stream time_base {%d, %d}",
            aud_stream.context->time_base.num,
            aud_stream.context->time_base.den);
    }

    if (vid_stream.stream_id != -1) {
        LOGD("Video stream time_base {%d, %d}",
            vid_stream.context->time_base.num,
            vid_stream.context->time_base.den);
    }

    LOGI("Starting packet and decode threads");

    thread_quit = false;

    pthread_create(&thread_packet, NULL, &FFMPEG::thread_packet_function, this);

    Display.set_overlay_timout(3.0);

    return true;
}
AVPacket packet;
av_init_packet(&packet);
packet.data = myTSpacketdata; // pointer to the TS packet
packet.size = 188;

You should be able to reuse the packet. And it might need unref'ing.

Wow, that looks great. Thanks. Just to confirm, your "packet_list" and "packets" are MPEG-TS packets? With 0x47 sync byte, PID, TS header, etc?

Yes they are the packets received from av_read_frame(). There's no need to check sync byte, only the stream ID as in the packet thread.

NB: I noticed a difference between ffmpeg 3.1.4 and 3.2. The early version gave 1 to 1 packets for the decoder. 3.2 have smaller packets as ffmpeg has now decoupled and deprecated the avcodec_decode_video2() function into 2 separate calls. Either way, this makes no difference because you just check the &got variable.

And another note as you mentioned about the raw TS packets. Yes you can feed the decoder with those packets too just so long as you identify the correct stream ID.

I've used your code to make a simple test program. To simulate the in-memory transfer, I read from a file containing only TS packets of the Video PID. I think I'm close but don't know how to set up the FormatContext. Sample cost posted above... any ideas?

c++ - What to pass to avcodec_decode_video2 for H.264 Transport Stream...

c++ ffmpeg video-processing
Rectangle 27 1

netstat | grep -P '(tcp|udp)'

You may want to use the i flag to ignore the case if necessary.

netstat | grep -Pi '(TcP|UDp)'

About the other answer here, using egrep or grep -e gives the same result. Based on this.

The -P flag was inspired by this post.

Using the option -P, accordingly to man grep, sets the pattern interpreter as perl. Not sure why it did not work without -P though.

Good answer, the -e comment should have been a comment to my post rather than being included in your answer though.

Oh, sorry, should have noticed that. Well at least you got ten points from my upvote. Keep up the good work and you'll have the reputation soon. Try to also markup your posts so they are readable and understandable, this will only improve the quality of your posts. More information here.

regex - regular expression with grep not working? - Stack Overflow

regex grep udp cygwin
Rectangle 27 0

Made a fundamental mistake. With ConnectionlessBootstrap everything runs over the same channel and we were closing the channel after each call to the server...thus disabling UDP. That's what our TCP code does and it took a while to realize it works differently. Hope someone else saves some time and headaches off of this.

java - UDP with netty different pipeline per remote host not working -...

java network-programming netty nio
Rectangle 27 0

Mike, your code does not work because you are trying to send the UDP associate command through the a UDP datagram. The SOCKS5 handshake must be over a TCP control connection.

Your server may need to keep one open TCP connection per client, but each client does not need many TCP connections open - one TCP connection can handle any number of UDP associate commands.

If your sole purpose is to not use TCP at all on the server side, it will not achieve what you want. The TCP connection is needed so that the SOCKS proxy knows when to disassociate the UDP ports (namely, when the TCP connection goes down).

However, your server application does not need to worry about this at all. The TCP control connection terminates at the SOCKS server just as your diagram shows.

c++ - Sending UDP packets through SOCKS proxy - Stack Overflow

c++ sockets proxy winsock socks
Rectangle 27 0

Also you could send UDP multicast over the network. And count number of working clients. (ReSharper use this trick) here is sample code

_receiveClient = new UdpClient();

Socket s = _receiveClient.Client;

const int optionValue = 1;
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue);

s.ReceiveBufferSize = 256*1024;
s.ReceiveTimeout = 2000;
s.Bind(new IPEndPoint(IPAddress.Any, _uri.Port));

_receiveClient.JoinMulticastGroup(_groupAddress, 2);

c# - How to check license validation for N computers - Stack Overflow

c# .net licensing
Rectangle 27 0

I work on a product that supports both UDP (IP) and TCP/IP communication between client and server. It started out with IPX over 15 years ago with IP support added 13 years ago. We added TCP/IP support 3 or 4 years ago. Wild guess coming up: The UDP to TCP code ratio is probably about 80/20. The product is a database server, so reliability is critical. We have to handle all of the issues imposed by UDP (packet loss, packet doubling, packet order, etc.) already mentioned in other answers. There are rarely any problems, but they do sometimes occur and so must be handled. The benefit to supporting UDP is that we are able to customize it a bit to our own usage and tweak a bit more performance out of it.

Every network is going to be different, but the UDP communication protocol is generally a little bit faster for us. The skeptical reader will rightly question whether we implemented everything correctly. Plus, what can you expect from a guy with a 2 digit rep? Nonetheless, I just now ran a test out of curiosity. The test read 1 million records (select * from sometable). I set the number of records to return with each individual client request to be 1, 10, and then 100 (three test runs with each protocol). The server was only two hops away over a 100Mbit LAN. The numbers seemed to agree with what others have found in the past (UDP is about 5% faster in most situations). The total times in milliseconds were as follows for this particular test:

The total data amount transmitted was about the same for both IP and TCP. We have extra overhead with the UDP communications because we have some of the same stuff that you get for "free" with TCP/IP (checksums, sequence numbers, etc.). For example, Wireshark showed that a request for the next set of records was 80 bytes with UDP and 84 bytes with TCP.

networking - When is it appropriate to use UDP instead of TCP? - Stack...

networking tcp udp
Rectangle 27 0

if you can read the ip packet header info, you can get it done. In ip packet header includes the next protocol no(6 means TCP,17 means UDP), you should use this to differentiate.

It depands on your hardware. If your machine is switch or router, it's a piece of cake. Else if yours is PC or Server, as your word, it will decrease the performance rather than non-reading every pkt proccessing. My ex job is tester about the network product, and i dont know any other way to slove your problem, sorry.

@2vision2 - have you actually thought through your requirements? Because you've stated a very clear requirement to log each packet, then you say it will decrease performance if you read each packet. How do you expect to log them without reading them?

if you are just reading packets headers and not bodies, it really isn't that hard, but if all you need to do is log this info, something like tcpdump or ngrep might solve your problem without having to write much if any code. but as @parsifal says, I think you need to further refine your actual requirements.

sockets - How to differentiate TCP and UDP packets in machine with jav...

java sockets java-ee tcp udp
Rectangle 27 0

Check chapter 9 of the ACE Programmers Guide (see http://www.orbzone.org/documents/books) for how UDP works with ACE. See ACE_wrappers/examples/APG/Misc_IPC for the code that belongs to that section.

sockets - c++ how do I receive stream packets from internet site to my...

c++ sockets networking stream ace
Rectangle 27 0

Firstly, assuming that your IP and other codes you write but not in above is correct,I have done a lot of test, even tried to change the settings of the firewall.But it still works. So, I think that maybe because of the unreliability of UDP protocol, your server sometimes can not receive the data from the client.You can just try to use TCP protocol.

Secondly, in your screenshot of PcWinTech.com v3.0.0 , it seems that your computer is in the subnetwork. So I gust that maybe the IP("72.49.50.49") is your router's IP, and I suggest you to check the settings of the router whether the router can transmit the data to your computer ,say, port forwarding.And I have just find a article that may help you.

wasn't me... anyway I also tried port forwarding but I'll read the article for more info

Probably because you don't provide a concrete answer but rather a list of assumptions and recommendations; things typically better as comments. Not the -1 either.

@ChiefTwoPencils yeah,,,may be you are right. I have been thinking about this question for all morning, doing a lot of test. But finally I can just get this two assumptions...Anyway, thanks for your comments.

@JoeBoris after trying port forwarding ,can it still not work?Maybe you can try to run your server and client program in the same subnetwork at first, in order to check if there is something wrong with the existing code.

networking - Java DatagramSocket sending but not receiving - Stack Ove...

java networking datagram
Rectangle 27 0

UDP scan works by sending a UDP packet to every targeted port. For some common ports such as 53 and 161, a protocol-specific payload is sent, but for most ports the packet is empty. The --data-length option can be used to send a fixed-length random payload to every port or (if you specify a value of 0) to disable payloads. If an ICMP port unreachable error (type 3, code 3) is returned, the port is closed. Other ICMP unreachable errors (type 3, codes 1, 2, 9, 10, or 13) mark the port as filtered. Occasionally, a service will respond with a UDP packet, proving that it is open. If no response is received after retransmissions, the port is classified as open|filtered. This means that the port could be open, or perhaps packet filters are blocking the communication. Version detection (-sV) can be used to help differentiate the truly open ports from the filtered ones.

You can read the full article here: NMAP port scanning

Ok I see, I found another link that goes in the same direction than your answer: stackoverflow.com/a/9265820/397830

c# - Check if a remote port is UP(listening) on UDP? - Stack Overflow

c# .net udp
Rectangle 27 0

The yaSSL and CyaSSL embedded SSL/TLS libraries have worked well for me in the past. Being targeted at embedded systems, they are optimized for both speed and size. yaSSL is written in C++ and CyaSSL is written in C. In comparison, CyaSSL can be up to 20 times smaller than OpenSSL.

Both support the most current industry standards (up to TLS 1.2), offer some cool features such as stream ciphers, and are dual licensed under the GPLv2 and a commercial license (if you need commercial support).

Hi Chris, thanks for the answer. Unfortunately, over a year has passed since my posting, and the client canceled the project and tossed me off of the project a couple of weeks ago.

c++ - Adding SSL support to existing TCP & UDP code? - Stack Overflow

c++ ssl udp tcp ssl-certificate
Rectangle 27 0

getsockname might get it for you, but I wonder why your code works with a UDP socket.

"bind() works fine with UDP sockets" -- of course. "local.sin_port = 0; //randomly selected port" -- MSDN only documents that for TCP.

MSDN documents in SendTo that it will auto-Bind for UDP, if you haven't already.

@JesseChisholm: the MSDN documentation for sendto() states that an implicit bind() is performed only if setsockopt() was also called beforehand.

How to find a socket's local port number? (Windows C++) - Stack Overfl...

c++ windows sockets binding port
Rectangle 27 0

I have the same problem, udp socket does not receive scapy packet. I suppose there might be something related to this post: Raw Socket Help: Why UDP packets created by raw sockets are not being recieved by kernel UDP? And what works for me is the socket.IP_HDRINCL option. Here is the working code for both and sender.

import socket
from scapy.all import *

rawudp=socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
rawudp.bind(('0.0.0.0',56789))
rawudp.setsockopt(socket.SOL_IP, socket.IP_HDRINCL,1)

pkt = IP()/UDP(sport=56789, dport=7890)/'hello'

rawudp.sendto(pkt.build(), ('127.0.0.1',7890))
import socket
so = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
so.bind(('0.0.0.0',7890))
while True:
    print so.recv(1024)

Talking to C socket with Scapy - Stack Overflow

c sockets networking scapy localserversocket
Rectangle 27 0

Your python client code looks suspicious, I don't think you should be doing a connect or a send using a UDP socket. Try this:

#!/usr/bin/python

import socket, sys, time, struct

port = 10000
host = "localhost"
addr = (host,port)

if len(sys.argv) > 1:
    host = sys.argv[1]

print "Sending Data"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.sendto("Hello World",addr)

print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
while 1:
    data,addr = s.recvfrom(1200)
    if not data:
        break
    print "Received: %s" % data

it works for me using your server.cpp

macmini:stackoverflow samm$ ./client.py 
Sending Data
Looking for replies; press Ctrl-C or Ctrl-Break to stop.
Received: Hello World

host unreachable is what I would expect if the client that sent the message does not have the sender_endpoint_ port open. When I compiled your server.cc and use the Boost.Asio blocking udp echo client example, it works just fine

macmini:stackoverflow samm$ g++ server.cpp -lboost_system -o server
macmini:stackoverflow samm$ g++ client.cpp -lboost_system -o client
macmini:stackoverflow samm$ ./server 10000

in another shell

macmini:stackoverflow samm$ ./client 127.0.0.1 10000
Enter message: hello
Reply is: hello
macmini:stackoverflow samm$ ./client 127.0.0.1 10000
Enter message: goodbye
Reply is: goodbye
macmini:stackoverflow samm$

hmmm, thats odd. I tried it with the UDP client also. I think it might be something to do with the python test script I'm using.

c++ - Why doesn't this Boost ASIO code work with this python client? -...

c++ python boost-asio
Rectangle 27 0

I tried you code. It worked. (Of course, just the TCP/UDP parts. Rest commented out):

Correctly reached the udp part of the server Correctly reached the tcp part of the server

Capture tcpdump on the client and server side. Examine the traces.

Is the UDP client really sending the packet?

As suggested by WalterA in comments, have \n in the printf

c - Issues when writing a server that handles both TCP and UDP server ...

c sockets unix tcp udp