Python unix socket file

What are .sock files and how to communicate with them

Elaborating on the 2nd bullet, I understand that .sock files are for Inter-process communication. How can I ‘communicate’ with them? Let us say a sock file is designed to respond in a specific way (For ex: it takes the input ‘time’ and prints out the current time).

I prefer higher level programming languages (python) more than C/C++ . It’d also be better if someone can point me to some application (like nc maybe?) that I can use to communicate with .sock files in a quick and dirty way?

Please supply some context so we know what you’re asking about. Where did you encounter a ‘.sock’ file?

James, the .sock file has been preprogrammed to provide a «challenge-response» algorithm. For ex: Me to .sock: «MyUserName» .sock to me: «Here is your token: a_token». I need to figure out how to communicate with the .sock in a bidirectional way

Hello and welcome on StackOverflow. In order to get your a better answer, and your answer don’t get deleted later on, you would have to read and follow some basic rules and conventions that will help everyone to communicate and help better. Please go to stackoverflow.com/help and read about the topic «What topics can I ask about here?», and «What types of questions should I avoid asking?».

2 Answers 2

Sock files are socket files they are endpoints in communication pipes.

how to create socket files:

  • let uwsgi create them when interacting with servers(e.g. nginx) sudo uwsgi —ini /path/to/ini/file/ In the ini file you need to have passed a path to where you want to add the socket file .ini files will on unix sysytems live at /etc/uwsgi/sites/*.ini
  • create socket files using a high level language try python: python -c «import socket as s; sock = s.socket(s.AF_UNIX); sock.bind(‘/tmp/test.sock’)»
  • use nc Server side have: nc -l -p 1234 Client side have: nc -l -p 1234 That way you have a open socket that can communicate. I leave this here

Here’s detailed info on working with sockets in Python

You can communicate with sockets using netcat-openbsd or socat

UPDATE: here’s an example of a socket server taken from the first link

import socket import sys import os server_address = './uds_socket' # Make sure the socket does not already exist try: os.unlink(server_address) except OSError: if os.path.exists(server_address): raise # Create a UDS socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # Bind the socket to the port print >>sys.stderr, 'starting up on %s' % server_address sock.bind(server_address) # Listen for incoming connections sock.listen(1) while True: # Wait for a connection print >>sys.stderr, 'waiting for a connection' connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it while True: data = connection.recv(16) print >>sys.stderr, 'received "%s"' % data if data: print >>sys.stderr, 'sending data back to the client' connection.sendall(data.upper()) else: print >>sys.stderr, 'no more data from', client_address break finally: # Clean up the connection connection.close() 

save this into a file called sock.py and run

~/Development/temp ᐅ python sock.py starting up on ./uds_socket waiting for a connection 

then connect using socat

~/Development/temp ᐅ socat - UNIX-CONNECT:uds_socket hello HELLO 

write something — and you’ll receive the same thing but in uppercase as a reply.

Читайте также:  Modbus tcp client python

Источник

Python 3.X Unix Socket Example [duplicate]

I have been searching the last couple of hours on finding a simple Server / Client Unix Socket Example. I have found examples for Python 2.X, but I am failing at finding one that works for Python 3.X. I keep getting TypeErrors. The example that I have been working with is: client.py

# -*- coding: utf-8 -*- import socket import os # import os, os.path print("Connecting. ") if os.path.exists("/tmp/python_unix_sockets_example"): client = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM ) client.connect("/tmp/python_unix_sockets_example") print("Ready.") print("Ctrl-C to quit.") print("Sending 'DONE' shuts down the server and quits.") while True: # try: x = input( "> " ) if "" != x: print("SEND:", x) client.send( x ) if "DONE" == x: print("Shutting down.") break # except KeyboardInterrupt, k: # print("Shutting down.") client.close() else: print("Couldn't Connect!") print("Done") 
  • With the client portion, I was not sure how to get a KeyboardInterupt to work in 3.X, so I killed the Try and Except portions. Any Advice?
  • Also, the syntax from the example I used had multiple modules being loaded from one import import os, os.path Is this the old way of only loading os.path from os module?
# -*- coding: utf-8 -*- import socket import os # import os, os.path # import time if os.path.exists("/tmp/python_unix_sockets_example"): os.remove("/tmp/python_unix_sockets_example") print("Opening socket. ") server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) server.bind("/tmp/python_unix_sockets_example") print("Listening. ") while True: datagram = server.recv(1024) if not datagram: break else: print("-" * 20) print(datagram) if "DONE" == datagram: break print("-" * 20) print("Shutting down. ") server.close() os.remove("/tmp/python_unix_sockets_example") print("Done") 
  • When I run this I get TypeError: ‘str’ does not support the buffer interface.
  • Does Python 3.4 Unix Sockets only support binary?
  • What is the easiest way to make this work?

Источник

How do you use Unix sockets in Python?

I want to use Unix sockets for 2 Python programs on the same system to talk to each other. There are examples of binding to a socket file here: https://gist.github.com/jmhobbs/11276249 The often-used socketserver library also has a UnixStreamServer, and a UnixDatagramServer, which sounds like it deals with unix sockets as well, but there are no examples of either one, and as far as I can tell, it requires an IP and Port, rather than a file when initializing either a UnixStreamServer or UnixDatagramServer. Are UnixDatagramServer and UnixStreamServer a different type of unix sockets that demonstrated here? Or am I just not seeing how to use them to connect to a socket file properly? Are there examples? Why would someone use UnixDatagramServer/UnixStreamServer over binding to a socket file directly, as in my link? And when talking about IP sockets, the difference between TCP/UDP makes sense — one is reliable, while the other is not, without the overhead. In a world of sockets, where I assume there’s no such thing as unreliable communication, why are there still 2 different types (Datagram vs Stream)?

Читайте также:  Move end in javascript

3 Answers 3

As @GreenCloakGuy pointed out, you may want to use Pipes, but if you’re set on using Unix sockets, here’s a rough example of using StreamRequestHandler:

#!/usr/bin/env python3 from socketserver import UnixStreamServer, StreamRequestHandler, ThreadingMixIn import os os.unlink("/tmp/test") class Handler(StreamRequestHandler): def handle(self): while True: msg = self.rfile.readline().strip() if msg: print("Data Recieved from client is: <>".format(msg)) else: return class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass with ThreadedUnixStreamServer('/tmp/test', Handler) as server: server.serve_forever() 
#!/usr/bin/env python3 import socket import sys import time with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: client.connect("/tmp/test") while True: client.send(b"Client 1: hi\n") time.sleep(1) client.close() 

The ThreadingMixIn isn’t necessary, but lets you run 2 clients, and receive messages from both of them at the same time. Copy the client code into «client1.py» and «client2.py», and change «Client 1» to «Client 2» in client2.py, running both, to see this in practice.

I’m no expert, but it sounds like while Pipes are more efficient, they have the disadvantage of having only one program linked to one other program. If you have multiple clients, and one server, Unix sockets, as demonstrated here, might be your best bet.

@CSQGB the fact that you don’t need to remember to close a resource is the primary reason to use a with statement, and that the with statement even exists, so no, you don’t need to close if you’re using with . It will close automatically when you exit the block

#!/usr/bin/env python2 # -*- coding: utf-8 -*- #kate: syntax Python ; # use them like so: import socket, os , time parent, child = socket.socketpair() #child.close() # bad fdesc pid = os.fork() if pid: #time.sleep(0.3) #child.close() print 'in parent, sending message' p = parent.sendall('ping p') response1 = parent.recv(444) print 'response from child :', response1 p = parent.close() else: #time.sleep(0.7) #parent.close() print 'in child, waiting for message' message1 = child.recv(333) print 'message from parent :', message1 child.sendall('päng c') child.close() #print "Ende" , pid #print parent # , child #print type(pid) , " -- " , type(child) 

for 2 Python programs on the same system to talk to each other

Don’t use sockets. Use pipes.

Читайте также:  Html link title seo

A socket, in particular, is essentially a link between the Application layer and the Transfer layer, in networking. This is why you need so supply an IP and port number — those are the important addressing information for anyone looking at your computer externally. It’s also why you have Datagram vs Stream — TCP and UDP are the two main transport layer protocols, and when building your link to the transport layer you need to specify which protocol you want to use. Sockets are meant for communication using the network — there are alternate, more efficient and easier, ways to communicate between two processes on the same system.

Pipes are more like file descriptors that are used specifically for inter-process communication. There are essentially two ways to use pipes — named pipes and anonymous pipes. If your «two python programs» are splitting off from one original program using something like multiprocessing , then anonymous pipes are what you might want to go with, and you can use os.pipe() to set that up. Otherwise, you’ll need to figure out a consistent name and location for your pipe that both programs know, and initialize it on one end with os.mkfifo() then just open it like a regular file on the other end. This functionality seems to only be available on Unix, so if you’re on Windows you might have to investigate other solutions.

Источник

Оцените статью