Can't read any data when connecting to Redis - linux

I have the following code with connects to Redis running locally on port 6379. The problem is that can't read any output, the reader thread just blocks on recvfrom(). Everything works fine with an echo server for example, but not with Redis.
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
struct sockaddr_in servAddr;
int sock;
/* Reader loop */
void *readerf(void *n) {
char buffer[128];
int bytesRcvd;
while((bytesRcvd = recvfrom(sock, buffer, 127, 0, NULL, 0)) > 0) {
printf("[%s]",buffer);
}
}
char *getk = "GET key\n";
char *setk = "SET key \"test\"\n";
void sendd(char *str) {
if (send(sock, str, strlen(str), 0) != strlen(str))
perror("Send error");
send(sock, "\0", 1, 0);
//printf("sent: [%s]",str);
}
int main(int argc, char *argv[]) {
int i = 1;
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return 1;
/* Construct the server address structure */
memset(&servAddr, 0, sizeof(servAddr)); /* Zero out structure */
servAddr.sin_family = AF_INET; /* Internet address family */
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* Server IP address */
servAddr.sin_port = htons(6379); /* Server port */
if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr))<0)
perror("Could not connect");
sendd(getk);
sendd(setk);
sendd(getk);
pthread_t reader;
pthread_create(&reader, NULL, readerf, &i);
sleep(5);
close(sock);
return 0;
}

It seems like you are not properly implementing Redis' protocol: http://redis.io/topics/protocol
If you are seriously coding a client, and not just investigating/having fun consider hiredis: https://github.com/antirez/hiredis/

Related

server only accept once and terminate

I'm learning Unix Network Programming in Chapter5, wait and waitpid functions. I test function wait. I run the server application firstly and then the client(repeat ./a.out several times). But the server can only accept the request one time and terminated. Errno is 4.
/* server.c
*
* gcc server.c -o server
* ./server & (run in background)
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <signal.h>
void sig_chld(int signum) // SIGCHLD handler
{
int stat;
pid_t pid;
pid = wait(&stat);
}
int main(void)
{
int listenfd;
int connfd;
struct sigaction act;
struct sockaddr_in addr;
socklen_t addrlen;
pid_t pid;
act.sa_handler = sig_chld; // register SIGCHLD handler
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGCHLD, &act, NULL);
addrlen = sizeof(addr);
bzero(&addr, addrlen); // fill server address
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_pton(AF_INET, "192.168.0.10", &addr.sin_addr.s_addr);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bind(listenfd, (struct sockaddr *)&addr, addrlen);
listen(listenfd, 5);
while (1) { // waiting for client request
connfd = accept(listenfd, (struct sockaddr *)&addr, &addrlen);
if (connfd < 0) {
printf("connect\n");
break;
}
pid = fork();
if (pid < 0) {
exit(-1);
} else if (pid == 0) { // child
close(listenfd);
write(connfd, "hello\n", 7);
exit(0);
}
else { // parent
close(connfd);
}
}
return 0;
}
/* client.c
*
* gcc client.c
* ./a.out (repeat several times)
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <errno.h>
#define MAXLINE 4096
int main(void)
{
char buf[1024];
int cliefd;
struct sockaddr_in servaddr;
socklen_t addrlen;
addrlen = sizeof(servaddr);
bzero(&servaddr, addrlen); // fill server address
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8080);
inet_pton(AF_INET, "192.168.0.10", &servaddr.sin_addr.s_addr);
cliefd = socket(AF_INET, SOCK_STREAM, 0);
if (connect(cliefd, (struct sockaddr *)&servaddr, addrlen) < 0) {
printf("error: %d\n", errno);
exit(-1);
}
read(cliefd, buf, MAXLINE);
fputs(buf, stdout);
return 0;
}
errno value 4 is EINTR. This indicates that a system call was interrupted. In this case, the SIGCHLD is interrupting the accept system call. Keep reading further in that chapter. Below is a quote from it which specifically points that out for this particular example code:
Since the signal was caught by the parent while the parent was blocked in a slow system call (accept), the kernel causes accept to return an error of EINTR (interrupted system call). The parent does not handle this error so it aborts.
The purpose of this example is to show that when writing network programs that catch signals, we must be cognizant of interrupted system calls, and we must handle them.
It goes on further to explain how the signal can be set up to automatically restart interrupted system calls. In summary, set the SA_RESTART flag in the act.sa_flags field:
act.sa_flags |= SA_RESTART;

Net Link Linux User code bind socket call always fail for multicast group Id (non zero value)

Hi am trying to implement net link user code and kernel code every thing works fine for unicast (src_addr.nl_groups = 0;). For mulicast, user code bind call always fails for non zero src_addr.nl_groups value. Really am not sure what value to put for multicast and how to proceed further. I checked the usage of netlink_broadcast in kernel source tree, so I put the same group Id value (RTMGRP_LINK) here. For unicast I found good number of help in internet but for multicast I don't think so . So Please help me to proceed further.
Error am getting is:
bind: No such file or directory
./a.out: can't bind socket (3)and err : -1: No such file or directory
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdio.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#define NETLINK_TEST 28
#define GROUP_IB 1
#define MAX_PAYLOAD 1024
struct sockaddr_nl src_addr, dst_addr;
struct nlmsghdr *nlh = NULL;
struct msghdr msg;
struct iovec iov;
int sock_fd;
int main(int argc, char ** argv)
{
int err;
sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TEST);
if (sock_fd<0) {
char s[BUFSIZ];
sprintf( s, "%s: can't assign fd for socket", argv[0] );
perror(s);
return -1;
}
memset(&src_addr, 0, sizeof(src_addr));
src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid();
src_addr.nl_groups = 0; // Unicast
//src_addr.nl_groups = RTMGRP_LINK; /* Multicast, bind call always fails for non zero values */
err = bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
perror("bind");
if (err<0) {
char s[BUFSIZ];
sprintf( s, "%s: can't bind socket (%d)and err : %d", argv[0], sock_fd,err );
perror(s);
return -1;
}
memset(&dst_addr, 0, sizeof(dst_addr));
nlh = (struct nlhmsghdr *) malloc(NLMSG_SPACE(MAX_PAYLOAD));
memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
iov.iov_base = (void *)nlh;
iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
msg.msg_name = (void *)&dst_addr;
msg.msg_namelen = sizeof(dst_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
printf("pid : %d\n Waiting for messages from kernel...\n",getpid());
recvmsg(sock_fd, &msg, 0);
printf("Message : %s\n", NLMSG_DATA(nlh));
close(sock_fd);
return 0;
}
Netlink socket binds are sensitive to what USER you are- I've seen them reliably fail if you are not running the program in question as 'root', at least on RedHat 6.
Try running as root 1st, before changing your logic. If you get the same failure as you do in normal operation, then you know it isn't (necessarily) a permissions issue.
The issue is
sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TEST);
Does you kernel module define the NETLINK_TEST family? your own family might must be supported at kernel module and it should post the message in the proper group using nlmsg_multicast()
RTMGRP_LINK is group defined in NETLINK_ROUTE.
This sample code is example for multicast
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <unistd.h>
#define MYPROTO NETLINK_USERSOCK
#define MYMGRP 21
int open_netlink(void)
{
int sock;
struct sockaddr_nl addr;
int group = MYMGRP;
sock = socket(AF_NETLINK, SOCK_RAW, MYPROTO);
if (sock < 0) {
printf("sock < 0.\n");
return sock;
}
memset((void *) &addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_pid = getpid();
/* addr.nl_groups = MYMGRP; */
if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
printf("bind < 0.\n");
return -1;
}
if (setsockopt(sock, 270, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) < 0) {
printf("setsockopt < 0\n");
return -1;
}
return sock;
}
void read_event(int sock)
{
struct sockaddr_nl nladdr;
struct msghdr msg;
struct iovec iov;
char buffer[65536];
int ret;
iov.iov_base = (void *) buffer;
iov.iov_len = sizeof(buffer);
msg.msg_name = (void *) &(nladdr);
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
printf("Ok, listening.\n");
ret = recvmsg(sock, &msg, 0);
if (ret < 0)
printf("ret < 0.\n");
else
printf("Received message payload: %s\n", NLMSG_DATA((struct nlmsghdr *) &buffer));
}
int main(int argc, char *argv[])
{
int nls;
nls = open_netlink();
if (nls < 0)
return nls;
while (1)
read_event(nls);
return 0;
}
kernel module:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netlink.h>
#include <net/netlink.h>
#include <net/net_namespace.h>
#define MYPROTO NETLINK_USERSOCK
#define MYGRP 21
static struct sock *nl_sk = NULL;
static void send_to_user(void)
{
struct sk_buff *skb;
struct nlmsghdr *nlh;
char *msg = "Hello from kernel";
int msg_size = strlen(msg) + 1;
int res;
pr_info("Creating skb.\n");
skb = nlmsg_new(NLMSG_ALIGN(msg_size + 1), GFP_KERNEL);
if (!skb) {
pr_err("Allocation failure.\n");
return;
}
nlh = nlmsg_put(skb, 0, 1, NLMSG_DONE, msg_size + 1, 0);
strcpy(nlmsg_data(nlh), msg);
pr_info("Sending skb.\n");
res = nlmsg_multicast(nl_sk, skb, 0, MYGRP, GFP_KERNEL);
if (res < 0)
pr_info("nlmsg_multicast() error: %d\n", res);
else
pr_info("Success.\n");
}
static int __init hello_init(void)
{
pr_info("Inserting hello module.\n");
nl_sk = netlink_kernel_create(&init_net, MYPROTO, NULL);
if (!nl_sk) {
pr_err("Error creating socket.\n");
return -10;
}
send_to_user();
netlink_kernel_release(nl_sk);
return 0;
}
static void __exit hello_exit(void)
{
pr_info("Exiting hello module.\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");

Why does tcpdump enable this code to work?

I have a small network consisting of 2 hosts (OS X and linux) with a switch between them. When I run the following pair of programs, the receiver (linux) doesn't see any multicast packets. However, when I run
tcpdump -i eth0 -s 512 udp
on the linux box, everything starts to work. Can someone tell me why running tcpdump enables this to work?
Note that both machines have IPv6 enabled (if that matters). The host addresses in the code are the IPv4 addresses of the local interfaces.
On the OS X machine, I run:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUFLEN 256
int s;
int count;
struct in_addr local_address;
struct sockaddr_in multicast_address;
char buffer[BUFLEN];
int
main (int argc, char *argv[]) {
int port = 12345;
int retval = 0;
char *host_ip = "192.168.1.31";
char *multicast_ip = "224.0.0.251";
count = (int)time(NULL);
s = socket(AF_INET, SOCK_DGRAM, 0);
printf("s=%d\n", s);
local_address.s_addr = inet_addr(host_ip);
retval = setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, (char *)&local_address, sizeof(local_address));
printf("setsockopt=%d\n", retval);
memset((char *)&multicast_address, 0, sizeof(multicast_address));
multicast_address.sin_family = AF_INET;
multicast_address.sin_addr.s_addr = inet_addr(multicast_ip);
multicast_address.sin_port = htons(port);
while (1) {
sprintf(buffer, "Message number %d", count);
count++;
retval = sendto(s, buffer, BUFLEN, 0, (struct sockaddr*)&multicast_address, sizeof(multicast_address));
printf("sendto=%d\n", retval);
sleep(3);
}
return 0;
}
On the linux box, I run:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUFLEN 256
int s;
struct ip_mreq multicast_group;
struct sockaddr_in localSock;
char buffer[BUFLEN];
int
main(int argc, char *argv[]) {
int reuse = 1;
int retval = 0;
int port = 12345;
char *host_ip = "192.168.1.131";
char *multicast_ip = "224.0.0.251";
s = socket(AF_INET, SOCK_DGRAM, 0);
printf("s = %d\n", s);
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
printf("REUSEADDR = %d\n", retval);
memset((char *) &localSock, 0, sizeof(localSock));
localSock.sin_family = AF_INET;
localSock.sin_port = htons(port);
localSock.sin_addr.s_addr = INADDR_ANY;
retval = bind(s, (struct sockaddr*)&localSock, sizeof(localSock));
printf("bind = %d\n", retval);
multicast_group.imr_multiaddr.s_addr = inet_addr(multicast_ip);
multicast_group.imr_interface.s_addr = inet_addr(host_ip);
retval = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&multicast_group, sizeof(multicast_group));
printf("ADD_MEMBERSHIP = %d\n", retval);
while (1) {
retval = read(s, buffer, BUFLEN);
printf("%d => [%s]\n", retval, buffer);
}
return 0;
}
Thanks.

Is raw socket on loopback interface possible?

We are trying to communicate with the server listening on Linux loopback interface via raw socket and it seems like the server does not get a single packet from us. The packets we send are visible in Wireshark.
Is raw socket on loopback possible at all? (Please, don't ask why we need it: it's too complicated to explain here)
EDIT: this is how we open it
_I_RawSocket = socket( PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))
memset( &ifr, 0, sizeof( ifr ) );
strcpy( ifr.ifr_ifrn.ifrn_name, _InterfaceName);
ioctl( _I_RawSocket, SIOCGIFINDEX, &ifr )
memset( &sll, 0, sizeof( sll ) );
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons( ETH_P_ALL );
bind( _I_RawSocket, (struct sockaddr *) &sll, sizeof( sll ))
The server is lighttpd and it's reachable via normal socket on localhost.
netstat --raw prints empty table but I'm absolutely sure we have two functional raw sockets on normal eth devices.
Raw sockets behave particularly fizzy with bind() and connect(), but I can't confirm that your issue lies with them. I suggest you follow a more straightforward approach:
Sender
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define DEST "127.0.0.1"
int main(int argc, char **argv)
{
int s;
struct sockaddr_in dst_addr;
char packet[50];
struct iphdr *ip = (struct iphdr *)packet;
if((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("error:");
exit(EXIT_FAILURE);
}
dst_addr.sin_family = AF_INET;
dst_addr.sin_port = 0; /* not needed in SOCK_RAW */
inet_pton(AF_INET, DEST, (struct in_addr *)&dst_addr.sin_addr.s_addr);
memset(dst_addr.sin_zero, 0, sizeof(dst_addr.sin_zero));
memset(packet, 'A', sizeof(packet)); /* payload will be all As */
ip->ihl = 5;
ip->version = 4;
ip->tos = 0;
ip->tot_len = htons(40);
ip->frag_off = 0; /* NF */
ip->ttl = 64;
ip->protocol = IPPROTO_RAW; /* this has to be IPPROTO_RAW */
ip->check = 0;
ip->saddr = dst_addr.sin_addr.s_addr;
ip->daddr = dst_addr.sin_addr.s_addr;
while(42) {
sleep(5);
if (sendto(s, packet, sizeof(packet), 0,
(struct sockaddr *)&dst_addr, (socklen_t)sizeof(dst_addr)) < 0)
perror("uh oh:");
}
return(0);
}
Receiver
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int s;
struct sockaddr_in src_addr;
char packet[50];
if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("error:");
exit(EXIT_FAILURE);
}
memset(packet, 0, sizeof(packet));
socklen_t *len = (socklen_t *)sizeof(src_addr);
int fromlen = sizeof(src_addr);
while(42) {
if (recvfrom(s, &packet, sizeof(packet), 0,
(struct sockaddr *)&src_addr, &fromlen) < 0)
perror("uh oh:");
int i = sizeof(struct iphdr); /* print the payload */
for(; i < sizeof(packet); i++) {
printf("%c", packet[i]);
}
printf("\n");
}
return(0);
}
I hope these behave exactly like you want them to. Read man 7 raw for the gory details of why this works and more importantly man 7 packet if you want to extend it. Also, take note that IPPROTO_RAW implies the IP_HDRINCL socket option, which is why we're constructing the ip header ourselves - although the IP checksum and total length are computed and filled in by the kernel, still.
edit: In addition, if you wanted a raw socket with which to send valid data to an application like lighttpd, you'd have to match the protocol argument to socket() as well as provide valid values for the IP header fields. A proper ethernet header is not mandatory - the only important field will be filled for you by the kernel stack.
Please make sure bind to if_index
if (ioctl(sock, SIOCGIFINDEX, &stEthReq ) < 0 )
{
printf( "failed to get IF index!" );
return -1;
}
memset(&client_addr, 0, sizeof(client_addr));
client_addr.sll_family = AF_PACKET;
client_addr.sll_ifindex = stEthReq.ifr_ifru.ifru_ivalue;
client_addr.sll_protocol = VOS_HTONS(usEthType);
ret = bind(sock,(struct sockaddr *)(&client_addr), sizeof(client_addr));

How to UDP Broadcast with C in Linux?

How to UDP Broadcast with C in Linux?
In many IP stack, such as Linux, this code does not work. Your socket must have broadcast permissions. Try this:
bcast_sock = socket(AF_INET, SOCK_DGRAM, 0);
int broadcastEnable=1;
int ret=setsockopt(bcast_sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
/* Add other code, sockaddr, sendto() etc. */
Unwind has it right, except you should use 'sendto'
Here is an example, that assumes you already have a socket. It was taken from clamav
static void
broadcast(const char *mess)
{
#define BROADCAST_PORT 30000u
struct sockaddr_in s;
int broadcastSock = socket(AF_INET, SOCK_DGRAM, 0);
if(broadcastSock < 0)
return;
memset(&s, '\0', sizeof(struct sockaddr_in));
s.sin_family = AF_INET;
s.sin_port = htons(BROADCAST_PORT)
s.sin_addr.s_addr = INADDR_BROADCAST; /* This is not correct : htonl(INADDR_BROADCAST); */
cli_dbgmsg("broadcast %s to %d\n", mess, broadcastSock);
if(sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&s, sizeof(struct sockaddr_in)) < 0)
perror("sendto");
}
Typically using the Berkeley sockets API, to sendto() one or more datagrams to a known broadcast-class IP address.
I wrote udp multicast server recently for testing. To subscribe to multicast you would subscribe your client to Multicast group 225.0.0.37 port 12346 and port 12345 (2 feeds - one feeds sends "Hello, World!" the other one "Bye, Office!").
I've been using it for testing my client, both client and server run on the same box so there might be bits that may not work but give it a try first.
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#define BYE_OFFICE 12346
#define HELLO_PORT 12345
#define HELLO_GROUP "225.0.0.37"
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
struct sockaddr_in addr2;
int fd;
int fd2;
char *message = "Hello, World!";
char *message2 = "Bye, Office!";
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(1);
}
if ((fd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
exit(1);
}
/* set up destination address */
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(HELLO_GROUP);
addr.sin_port=htons(HELLO_PORT);
memset(&addr2,0,sizeof(addr2));
addr2.sin_family = AF_INET;
addr2.sin_addr.s_addr = inet_addr(HELLO_GROUP);
addr2.sin_port=htons(BYE_OFFICE);
while (1)
{
if (sendto(fd, message, strlen(message), 0,(struct sockaddr *) &addr, sizeof(addr)) < 0)
{
perror("sendto");
exit(1);
}
sleep(3);
if (sendto(fd2, message2, strlen(message2), 0,(struct sockaddr *) &addr2, sizeof(addr2)) < 0)
{
perror("sendto2");
exit(1);
}
sleep(3);
}
}

Resources