Read socket file linux

read / write on socket descriptors linux c

I am trying to send the contents of a file from the server to the client , I am reading the file line by line using fgets and writing to the socket descriptor line by line , on the client side , i am in an a while loop , reading the sent contents.I am not being able to terminate the server sending sequence , i.e the client keeps reading the buffer and the next program line is not executed , I think thers something wrong with my way of sending or recieving . here is the code :

server : filefd = fopen("clients.txt","a+"); while(fgets(filcont,300,filefd) != NULL) fclose(filefd); client side : while(n>0)

printf(«Enter peer name ( except yours ) to send connection request : \n»); the above line ( printf , peer name doesnot get executed until i terminate the server)

1 Answer 1

I was able to figure it out , I sent the file contents from the server using fread instead of fgets ( line by line ) and used a single read() at the client . this was the quick fix. But I also figured out another technique when in case you have to compulsorily use fgets , where the while loop at the client side makes the socket nonblocking for read and then blocking again , the code is pasted below.

flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); while(n>0) < n = read(sockfd,buffer,sizeof(buffer)-1); if(n==0) break; if(n==-1) printf("\nNon blocking read failed congrats"); printf("%s\n",buffer); memset(buffer,'\0',256); >printf("\nbytes read :%d \n",n); val = fcntl(sockfd, F_GETFL, 0); flags = O_NONBLOCK; val &= ~flags; // makes it blocking again fcntl(sockfd,F_SETFL,val); 

The code from stackoverflow was refered to make the socket blocking

Источник

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

I would like to implement a client-server architecture running on Linux using sockets and C/C++ language that is capable of sending and receiving files. Is there any library that makes this task easy? Could anyone please provide an example?

4 Answers 4

The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read into that buffer, and write from that buffer into your socket (you could also use send and recv , which are socket-specific ways of writing and reading data). The outline would look something like this:

while (1) < // Read data into buffer. We may not have enough to fill up buffer, so we // store how many bytes were actually read in bytes_read. int bytes_read = read(input_file, buffer, sizeof(buffer)); if (bytes_read == 0) // We're done reading from the file break; if (bytes_read < 0) < // handle errors >// You need a loop for the write, because not all of the data may be written // in one call; write will return how many bytes were written. p keeps // track of where in the buffer we are, while we decrement bytes_read // to keep track of how many bytes are left to write. void *p = buffer; while (bytes_read > 0) < int bytes_written = write(output_socket, p, bytes_read); if (bytes_written bytes_read -= bytes_written; p += bytes_written; > > 

Make sure to read the documentation for read and write carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue statement, while others mean something is broken and you need to stop.

Читайте также:  Linux как удалить логин

For sending the file to a socket, there is a system call, sendfile that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap (as in, be an actual file, not a socket), and the destination must be a socket (so you can’t use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn’t help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile call but no analogous recvfile .

Beware that sendfile is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile , but the exact interface may vary (FreeBSD, Mac OS X, Solaris).

In Linux 2.6.17, the splice system call was introduced, and as of 2.6.23 is used internally to implement sendfile . splice is a more general purpose API than sendfile . For a good description of splice and tee , see the rather good explanation from Linus himself. He points out how using splice is basically just like the loop above, using read and write , except that the buffer is in the kernel, so the data doesn’t have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as «zero-copy I/O»).

Читайте также:  Wsl install kali linux

Источник

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
Читайте также:  Install windows on linux partition

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.

Источник

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