3
votes

I've read something about port translation and now I want to test it.

I have a local machine behind a NAT router and a server with external IP address.

This is how I send packet from 5000th port on my machine to 4000th port on the server.

import socket
import sys

UDP_IP = #external server IP address
UDP_PORT = 4000
MESSAGE = "Hi!"

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind(('0.0.0.0', 5000))
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

Right after that I start to listen 5000th on local machine

import socket
import sys

UDP_IP = #my ip address in the local network
UDP_PORT = 5000

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print "received message:", data

On the server when I see incoming UDP from (someIP, somePort) I send response to the same someIP and somePort (use the same scripts with other port and address). But I never receive this response on my local machine. Why?

Also, this code is correctly work when server is in the local network.

2
Why don't you just use the same socket?David Schwartz

2 Answers

1
votes

The problem is that you are behind the NAT, the packet that you are sending to the server(which is external to the NAT) will have the source IP of the NAT server. The reply that the external server would send would have the destination IP of the NAT. When a reply comes to the NAT, it does not know what to do with that packet as there would be no address/port mapping available.
You should create a mapping on NAT saying the following
NAT Address:5000 <---> localaddress:5000

In this case the NAT would know that if it receives a packet at port 5000, it has to send that packet to you local machine.

1
votes

I've been in a similar situation (not getting responses from the server via UDP while client being behind the NAT), and what helped in my case was sending responses from the same port of the server that requests had been sent to. Different types of NATs work differently, and in my case the router must have built a strict mapping client:CLIENT_PORT <---> server:SERVER_PORT, so "responses" from the different port of the same server were declined. Maybe your case, too.