I spawn few processes using the Python multiprocessing module.
However when I call netstat -nptl, each ip:port listeners listed under the same PID.
I'm using Python 2.7 on Ubuntu 14.04.
netstat -V
>> net-tools 1.60
>> netstat 1.42 (2001-04-15)
Relevant code:
import unittest
import multiprocessing
import socket
import os
import time
import ex1
class Listener(multiprocessing.Process):
def __init__(self, _ttl):
super(Listener, self).__init__()
self.ttl = _ttl
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(('localhost', 0))
def get_pid(self):
return self.pid
def get_name(self):
return self.socket.getsockname()
def run(self):
self.socket.listen(1)
time.sleep(self.ttl)
def listen(self):
self.start()
class TestEx1(unittest.TestCase):
def test_is_legal_ip(self):
# Legal IP
assert(ex1.is_legal_ip("1.1.1.1:55555"))
assert(ex1.is_legal_ip("0.1.1.255:55555"))
assert(ex1.is_legal_ip("0.0.0.0:55555"))
assert(ex1.is_legal_ip("255.255.255.255:55555"))
assert(ex1.is_legal_ip("0.1.2.3:55555"))
# Illegal IP
assert(not ex1.is_legal_ip("256.1.1.1:55555"))
assert(not ex1.is_legal_ip("1.256.1:55555"))
assert(not ex1.is_legal_ip("1.1.1.1.1:55555"))
assert(not ex1.is_legal_ip("1.a.1.1:55555"))
assert(not ex1.is_legal_ip("1.1001.1.1:55555"))
def test_address_to_pid(self):
# Create 3 listener processes
listener1 = Listener(22)
listener2 = Listener(22)
listener3 = Listener(22)
# Start listening
listener1.listen()
listener2.listen()
listener3.listen()
print listener1.get_pid()
print listener2.get_pid()
print listener3.get_pid()
# For each listener, get appropriate ip:port
address1 = str(str(listener1.get_name()[0])) + \
":" + str(listener1.get_name()[1])
address2 = str(str(listener2.get_name()[0])) + \
":" + str(listener2.get_name()[1])
address3 = str(str(listener3.get_name()[0])) + \
":" + str(listener3.get_name()[1])
# Check if address_to_pid() works as expected.
#assert(str(ex1.address_to_pid(address1)) == str(listener1.get_pid()))
#assert(str(ex1.address_to_pid(address2)) == str(listener2.get_pid()))
#assert(str(ex1.address_to_pid(address3)) == str(listener3.get_pid()))
# Waits for the listener processes to finish
listener2.join()
listener2.join()
listener3.join()
if __name__ == "__main__":
unittest.main()
Output:
4193
4194
4195
..
----------------------------------------------------------------------
Ran 2 tests in 22.019s
OK
Netstat -nptl output:
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.1.1:53 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN -
tcp 0 0 127.0.0.1:37529 0.0.0.0:* LISTEN 4192/python
tcp 0 0 127.0.0.1:53402 0.0.0.0:* LISTEN 4192/python
tcp 0 0 127.0.0.1:49214 0.0.0.0:* LISTEN 4192/python
tcp 1 0 192.168.46.136:49475 209.20.75.76:80 CLOSE_WAIT 2968/plugin_host
tcp 70 0 192.168.46.136:60432 91.189.92.7:443 CLOSE_WAIT 3553/unity-scope-ho
tcp6 0 0 ::1:631 :::* LISTEN -
Using my Mac OS 10.9.5 (Python 2.7.3), I could reproduce the same behavior. After several try-and-error, it turned out that it's because the socket objects are shared among the processes. (lsof -p <pid> helps to identify listening sockets.)
When I made following change to Listener class, each process started to listen on its own port number by its own PID.
def get_name(self):
# this method cannot refer to socket object any more
# self.sockname should be initialized as "not-listening" at __init__
return self.sockname
def run(self):
# Instantiate socket at run
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(('localhost', 0))
self.sockname = self.socket.getsockname()
# Listener knows sockname
print self.sockname
self.socket.listen(1)
time.sleep(self.ttl)
This behavior should be the same as Ubuntu's Python and netstat.
self.sockname remains "not-listening" at original process
To listen on port as independent process, sockets need to be created at run method of a Listener object (New process calls this method after creating copy of the object). However variables updated in this copied object in the new process are not reflected to the original objects in original process.
Related
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
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.
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,
)
Hi I have been trying to set up an ejabberd cluster.
However on trying to join from node2 to node1 , i get an error saying
On node 2:
# ejabberdctl join_cluster ejabberd#<internal ip of node1>
Error: {no_ping,'ejabberd#<internal ip of node1>'}
I can clearly ping node1 from node2.
Both the node are hosted in the same region on AWS.
I have tried allowing all traffic on node 1.
Both have the same .erlang.cookie.
Not sure why i continue to get that error.
# ejabberdctl status
The node 'ejabberd#<internal ip of node1>' is started with status: started
ejabberd 16.03.107 is running in that node
# netstat -lnptu
tcp 0 0 0.0.0.0:4369 0.0.0.0:* LISTEN 2190/epmd
tcp 0 0 0.0.0.0:5269 0.0.0.0:* LISTEN 2233/beam.smp
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 975/sshd
tcp 0 0 0.0.0.0:52189 0.0.0.0:* LISTEN 2233/beam.smp
tcp 0 0 0.0.0.0:5280 0.0.0.0:* LISTEN 2233/beam.smp
tcp 0 0 0.0.0.0:5222 0.0.0.0:* LISTEN 2233/beam.smp
tcp6 0 0 :::4369 :::* LISTEN 2190/epmd
tcp6 0 0 :::22 :::* LISTEN 975/sshd
ejabberdctl.cfg on node1 :
ERLANG_NODE=ejabberd#<internal IP of node1>
ejabberd.yml on node1:
loglevel: 4
log_rotate_size: 10485760
log_rotate_date: ""
log_rotate_count: 1
log_rate_limit: 100
hosts:
- "<external ip of node1>"
listen:
-
port: 5222
module: ejabberd_c2s
max_stanza_size: 65536
shaper: c2s_shaper
access: c2s
-
port: 5269
module: ejabberd_s2s_in
-
port: 5280
module: ejabberd_http
request_handlers:
"/websocket": ejabberd_http_ws
web_admin: true
http_bind: true
captcha: true
auth_method: internal
shaper:
normal: 1000
fast: 50000
max_fsm_queue: 1000
acl:
local:
user_regexp: ""
loopback:
ip:
- "127.0.0.0/8"
access:
max_user_sessions:
all: 10
max_user_offline_messages:
admin: 5000
all: 100
local:
local: allow
c2s:
blocked: deny
all: allow
c2s_shaper:
admin: none
all: normal
s2s_shaper:
all: fast
announce:
admin: allow
configure:
admin: allow
muc_admin:
admin: allow
muc_create:
local: allow
muc:
all: allow
pubsub_createnode:
local: allow
register:
all: allow
trusted_network:
loopback: allow
language: "en"
modules:
mod_adhoc: {}
mod_announce: # recommends mod_adhoc
access: announce
mod_blocking: {} # requires mod_privacy
mod_caps: {}
mod_carboncopy: {}
mod_client_state: {}
mod_configure: {} # requires mod_adhoc
mod_disco: {}
mod_irc: {}
mod_http_bind: {}
mod_last: {}
mod_muc:
host: "conference.#HOST#"
access: muc
access_create: muc_create
access_persistent: muc_create
access_admin: muc_admin
mod_muc_admin: {}
mod_offline:
access_max_user_messages: max_user_offline_messages
mod_ping: {}
mod_privacy: {}
mod_private: {}
mod_pubsub:
access_createnode: pubsub_createnode
ignore_pep_from_offline: true
last_item_cache: false
plugins:
- "flat"
- "hometree"
- "pep" # pep requires mod_caps
mod_roster: {}
mod_shared_roster: {}
mod_stats: {}
mod_time: {}
mod_vcard:
search: false
mod_version: {}
allow_contrib_modules: true
I faced the same issue while setting up Ejabberd cluster on EC2. Here solution for reference.
Make sure following ports are open on internal/private network
5222 - xmpp client connection
5280 - web portal
4369 - EPMD
5269 - S2S
4200 - 4210 node communication
Also allow internal ping (icmp packets) just in case.
Next set FIREWALL_WINDOW option in ejabberdctl.cfg file as follows. This will set Erlang use a defined range of port instead of dynamic
ports for node communication. (refer ejabberdctl.cfg)
FIREWALL_WINDOW=4200-4210
And use full node names for you Ejabberd nodes eg: ejabberd#srv1.example.com
it seems you are missing configration in ejabberdctl.cfg change the following line in your ejabberdctl.cfg file-
#INET_DIST_INTERFACE=127.0.0.1 to
INET_DIST_INTERFACE=104.10.120.122 (whatever your host public ip)
and open erlang console and run the following command-
net_adm:ping('ejabberd#ejabberd1'). # your node
if it will return pong now you can do cluster between ejabberd nodes.
run the following command to make cluster-
ejabberdctl join_cluster 'ejabberd#ejabberd1'
Frist, #Uday Sawant's method is mandatory.
and also you should add each node info into /etc/hosts
for example, if your nodes are
ejabberd#node1
ejabberd#node2
set these to host file for two systems.
for os,
add your ejabbered node hostname
vi /etc/hosts
...
node1 10.0.100.1
node2 10.0.100.2
for erlang
vi $HOME/.hosts.erlang
'node1'.
'node2'.
host file for ejabberd
I have setup icecast 2 server and mpd too.
Both are working fine individually but icecast doesn't show the mpd in the mount list.
Here is my mpd.conf
# See: /usr/share/doc/mpd/mpdconf.example
user "ayush"
pid_file "~/.mpd/mpd.pid"
db_file "~/.mpd/mpd.db"
state_file "~/.mpd/mpdstate"
log_file "~/.mpd/mpd.log"
playlist_directory "~/.mpd/playlists"
music_directory "~/Music"
audio_output {
type "shout"
encoding "ogg"
name "stream"
host "localhost"
port "8000"
mount "/mpd.ogg"
bind_to_address "127.0.0.1"
# This is the source password in icecast.xml
password "pass"
# Set either quality or bit rate
# quality "5.0"
bitrate "128"
format "44100:16:2"
# Optional Parameters
user "source"
# description "here is my long description"
# genre "jazz"
} # end of audio_output
# Need this so that mpd still works if icecast is not running
audio_output {
type "alsa"
name "fake out"
driver "null"
}
Also here is the output of my netstat
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 315/sshd
tcp 0 0 0.0.0.0:17500 0.0.0.0:* LISTEN 651/dropbox
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 8006/icecast
tcp 0 0 0.0.0.0:16001 0.0.0.0:* LISTEN 1211/pulseaudio
tcp 0 0 0.0.0.0:57253 0.0.0.0:* LISTEN 1211/pulseaudio
tcp 0 0 0.0.0.0:60421 0.0.0.0:* LISTEN 1211/pulseaudio
tcp 0 0 0.0.0.0:4713 0.0.0.0:* LISTEN 1211/pulseaudio
tcp6 0 0 :::22 :::* LISTEN 315/sshd
tcp6 0 0 :::16001 :::* LISTEN 1211/pulseaudio
tcp6 0 0 :::36418 :::* LISTEN 1211/pulseaudio
tcp6 0 0 :::32899 :::* LISTEN 1211/pulseaudio
tcp6 0 0 :::6600 :::* LISTEN 8046/mpd
tcp6 0 0 :::4713 :::* LISTEN 1211/pulseaudio
My guess is that because mpd is not listening on ipv4 icecast is not able to see the mount point.
But I also don't understand why it doesn;t listen on ipv4 when I have explicitly used bind_to_address option.
Can someone please tell me how to make icecast see the mpd mountpoint.
Thanks
I was having the same issue and it seemed to stem from the setting bitrate "128" in mpd.conf. I was able to get the mountpoint to show up when I used quality "5.0".
I also tried bitrate "320" which did not work either, however I was able to see the mount with quality "10.0" as well. From this it seems that only the quality setting works.
I am not entirely sure, but I believe this stems from the way Vorbis is encoded. It seems like the encoders accept flags for quality in the form of -q {quality} where {quality} is any value from 0.0 to 10.0 (including factional values).
Sources:
https://en.wikipedia.org/wiki/Vorbis
http://linux.die.net/man/1/oggenc
I don't any problems connecting to icecast using the same settings, the only difference I see is the bind_to_address. This is used for connecting mpd clients if I'm not mistaken and not for the streaming server. It doesn't belong under audio_output.
Also, is there something in the MPD logs?