How can you force a web service client to use a specific port? - web-services

Is it possible to force an web service client to talk from a specific range of port E.g. 4900- 4999 to a web server in port 80?
I understand now that there is client and server port numbers and need to create a client application to send http statuses to a web server but firewall team only opens ports 4900 to 4999 in the client.
Any ideas?

If you are using a web browser to connect to your server then you may be out of luck but as you said in your question that you are creating a client application you can do this with the bind system call in both Windows and Linux (this code is in C):
struct sockaddr_in client;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&client, 0, sizeof(client));
client.sin_family = AF_INET;
client.sin_addr.s_addr = htonl(INADDR_ANY);
client.sin_port = htons(4901);
Then call bind:
res = bind(sock, (struct sockaddr *)&client, sizeof(client));
If this call is successful (res is 0) you can then connect your socket to the server and you will be connecting from port 4901.

In case someone else needs it, here is the Python code to do that:
#!/usr/bin/env python
from socket import *
import time
HOST = '**.**.**.**' # IP of the server
PORT = 8080
GET = '/hello/There'
BUFSIZ = 1024
ADDR = (HOST, PORT)
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(('',4925))
sock.connect(ADDR)
print 'connected'
request = """GET %s HTTP/1.0\n
Host: %s\n
User-Agent: Python\n
\n""" % (GET, HOST)
sock.send(request)
data = sock.recv(1024)
string = ""
while len(data):
string = string + data
data = sock.recv(1024)
print string
sock.close()
This is working with a wsgi server running on the other side. Pretty straight forward. Thanks for the help.

Related

How do I get the client Remote Port number in a Django?

I know I can use request.META['REMOTE_ADDR'] to get the client's IP in my django view function.
However, I have no idea how to get the client remote port number.
For example, you can see your own remote port number on the site below:
https://www.myip.com/
Remote Port
here is sample of view.py:
if request.user.is_authenticated:
        gelenIleti = request.META.get('HTTP_X_FORWARDED_FOR')
        if gelenIleti:
            ip = gelenIleti.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
            portNumarasi = request.META['SERVER_PORT']
        logger.info(' ' + 'LOG KAYDI :' + ' ' + ' KULLANICI : ' + request.user.username + ' ' + ' IP : ' + ip + ' ' + ' SERVER PORT : ' + portNumarasi)
You can get the IP and PORT through WSGIRequest connected socket.
Django 1.11:
sock = request._stream.stream._sock
client_ip, port = sock.getpeername()
Django 2.1:
sock = request._stream.stream.raw._sock
client_ip, port = sock.getpeername()
Django 2.2 and 3.1:
sock = request._stream.stream.stream.raw._sock
client_ip, port = sock.getpeername()
UPDATE
if request.user.is_authenticated:
sock = request._stream.stream.stream.raw._sock
client_ip, port = sock.getpeername()
logger.info(' LOG KAYDI : KULLANICI : %s IP : %s SERVER PORT : %s' % (request.user.username, client_ip, port))

Using CURLOPT_CONNECT_TO with an IPv6 address

I am attempting to use curl's CURLOPT_CONNECT_TO option to connect to a specific address (rather than the result of the DNS lookup of the host part of the url):
CURL * r_curl = NULL;
struct curl_slist * r_connect = NULL;
char connectStr[128];
if (af == AF_INET) {
sprintf(connectStr, "::%s:", ipAddrString);
} else if (af == AF_INET6) {
/* in [] per https://curl.haxx.se/libcurl/c/CURLOPT_CONNECT_TO.html */
sprintf(connectStr, "::[%s]:", ipAddrString);
}
fprintf(stderr, "DEBUG: connect '%s', url %s\n", connectStr, url);
r_curl = curl_easy_init();
...
r_connect = curl_slist_append(r_connect, connectStr);
curl_easy_setopt(r_curl, CURLOPT_CONNECT_TO, r_connect);
curl_easy_setopt(r_curl, CURLOPT_URL, url);
curl_easy_perform(r_curl);
When af is AF_INET and ipAddrSring is an IPv4 address this works perfectly. When af is AF_INET6 and ipAddrSring is an IPv6 address, curl looks like it is trying to do a DNS host lookup on the IPv6 address:
DEBUG: connect '::129.186.23.166:', url http://www.iastate.edu/
* Connecting to hostname: 129.186.23.166
* Trying 129.186.23.166...
* TCP_NODELAY set
* Connected to 129.186.23.166 (129.186.23.166) port 80 (#0)
vs
DEBUG: connect '::[2610:130:101:104::2]:', url http://www.iastate.edu/
* Connecting to hostname: 2610:130:101:104::2
* Could not resolve host: 2610:130:101:104::2
What I am doing wrong here?
(Curl is version 7.56.1)
There was a bug in libcurl (before 7.58.0) which made it take IPv6 addresses and attempt to use them for CURLOPT_CONNECT_TO, even if it was built without support for IPv6!
This was addressed in curl 7.58.0 and from then on it makes libcurl return an error if this is attempted!
Answer: Curl Library was built w/o IPv6 support.
I'm thinking that maybe that should result in a more meaningful error message.

Sending string via socket qpython3 android (client) to python2.7 linux (server)

Someone know how can I send string by socket qpython3 android (client) to python2.7 linux (server)?
For python2.7 linux (server) ok, I know, but I dont know how create the client with qpython3 android.
Someone Know?
TKS
My code for server in linux:
import socket
HOST = ''
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
tcp.bind(orig)
tcp.listen(1)
while True:
con, client = tcp.accept()
print 'Connected by', client
while True:
msg = con.recv(1024)
if not msg: break
print cliente, msg
print 'Ending client connection', client
con.close()
For client in android:
import sl4a
import socket
HOST = '127.0.0.1'
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)
print 'Press x to close'
msg = droid.dialogGetInput('Text', 'Input value').result
while msg <> 'x':
tcp.send ((msg).encode('utf-8'))
msg = droid.dialogGetInput('Text', 'Input value').result
tcp.close()
But this send erro on android:
socket.error: [Errno 111] Connection refused
Do U know wats happening?
Tks
It's your loopback address this wont work
HOST = '127.0.0.1'
Instead that use true ip address on network for your host and make sure port of 5000 on server is open already

ESP8266 NodeMCU Lua "Socket client" to "Python Server" connection not possible

I was trying to connect a NodeMCU Socket client program to a Python server program, but I was not able to establish a connection.
I tested a simple Python client server code and it worked well.
Python Server Code
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.send('Thank you for connecting')
c.close() # Close the connection
Python client code (with this I tested the above code)
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
s.send('Hi i am aslam')
print s.recv(1024)
s.close # Close the socket when done
The output server side was
Got connection from ('192.168.99.1', 65385)
Hi i am aslam
NodeMCU code
--set wifi as station
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--modify according your wireless router settings
wifi.sta.config("xxx", "xxx")
wifi.sta.connect()
function postThingSpeak()
print("hi")
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:connect(12345, "192.168.0.104")
srv:on("connection", function(sck, c)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
end
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() == nil then
print("Waiting for IP address...")
else
tmr.stop(1)
print("WiFi connection established, IP address: " .. wifi.sta.getip())
print("You have 3 seconds to abort")
print("Waiting...")
tmr.alarm(0, 3000, 0, postThingSpeak)
end
end)
But when I run the NodeMCU there is no response in the Python server.
The Output in the ESPlorer console looks like
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
WiFi connection established, IP address: 192.168.0.103
You have 3 seconds to abort
Waiting...
hi
Am I doing something wrong or missing some steps here?
Your guidance is appreciated.
After I revisited this for the second time it finally clicked. I must have scanned your Lua code too quickly the first time.
You need to set up all event handlers (srv:on) before you establish the connection. They may not fire otherwise - depending on how quickly the connection is established.
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:on("connection", function(sck)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
srv:connect(12345,"192.168.0.104")
The example in our API documentation is wrong but it's already fixed in the dev branch.

python SSL connection

I am doing a project in python which I need to implement client creating a ssl connection to a server I also implement.
I used ssl.wrapsocket(), but for some reason when I sniff the traffic using Wireshark I only see the TCP handshake.
Here is my client side code:
import socket
import ssl
import os
SERVER_ADDRESS = ('**********', 10000)
#open a TCP socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.settimeout(20000)
#connect to the server
client_sock.connect(SERVER_ADDRESS)
#start ssl handshake with the server
keyfile = os.path.dirname(__file__).replace('/', '\\') + '\\server.key'
certfile = os.path.dirname(__file__).replace('/', '\\') + '\\server.crt'
cli_ssl_sock = ssl.wrap_socket(
sock=client_sock,
certfile=certfile,
keyfile=keyfile,
server_side=False,
ssl_version=ssl.PROTOCOL_SSLv23,
ca_certs=None,
do_handshake_on_connect=False,
suppress_ragged_eofs=True,
)
cli_ssl_sock.do_handshake()
Here is my server side code:
import socket
import ssl
SERVER_ADDRESS = ('**********', 10000)
keyfile = '/root/Desktop/server.key'
certfile = '/root/Desktop/server.crt'
#create TCP socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket
server_sock.bind(SERVER_ADDRESS)
#listen
server_sock.listen(5)
print 'server is listening ...'
#receiving connections
while True:
conn_sock, client_address = server_sock.accept()
print 'new connection from : ' + str(client_address)
ssl_server_sock = ssl.wrap_socket(
sock=conn_sock,
certfile=certfile,
keyfile=keyfile,
server_side=True,
ssl_version=ssl.PROTOCOL_SSLv23,
ca_certs=None,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
)