I'm getting a few errors trying to make a simple unix socket program. So far, I have the server program working. I'm trying to write a programs that lets the client repeatedly send messages to the server program, and the server will display them. I've got two compiler windows open to test this. I'm getting errors that I assume are related to header files or unix specific stuff. I tried using, "sun_addr" instead of "sin_addr" (for unix), and it didn't work.
Errors...(EDITED FOR AFTER CHANGING ALL TO "UN" AND NOT "IN")
error:'struct sockaddr_un' has no member named 'sun_port'
Code...
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#define LEN 256
#define SOCKET_NAME "client_socket"
int main(void)
{
char message[LEN];
int sock;
struct sockaddr_un server_socket;
char server_reply[LEN];
//create af_unix/socket stream w/call to socket func
sock = socket(AF_UNIX , SOCK_STREAM , 0);
if(sock == -1)
{
perror("Could not create socket");
}
puts("Socket created");
//errors and warnings here...
server_socket.sun_family = AF_UNIX;
server_socket.sun_port = htons( 8888 );//or use sun_path?
if(connect(sock ,(struct sockaddr *)&server_socket, sizeof(server_socket))
<0)
{
perror("Connect failed.");
return 1;
}
puts("Connected\n");
while(1)
{
printf("Enter message : ");
scanf("%s" , message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if( recv(sock , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
puts(server_reply);
}
close(sock);
return 0;
}
This is the definition of sockaddr_un
and it doesn't have any members like sin_family and other that are reported in errors.
struct sockaddr_un{
short sun_family; /*AF_UNIX*/
char sun_PATH[108]; /*path name */
};
The structure you think you are using is this one
struct sockaddr_in {
short sin_family; /* AF_INET */
u_short sin_port; /* 16-bit port number */
struct in_addr sin_addr;
char sin_zero[8]; /* unused */
};
struct in_addr {
u_long s_addr; /*32-bit net id */
};
I think you are mixing the processing of families like AF_INET and AF_UNIX. Here is how to write for AF_INET.
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 12345
int main()
{
struct sockaddr_in addr;
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
printf("Error opening socket\n");
return -1;
}
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
if(bind(fd, (struct sockaddr *)&addr,sizeof(struct sockaddr_in) ) == -1)
{
printf("Error binding socket\n");
return -1;
}
printf("Successfully bound to port %u\n", PORT);
}
And for AF_UNIX, You can look at this and other related examples Client/Server Socket Communication (AF_UNIX)