Its a little lengthy.
Code:
/* function: implementation of 'ls' 1=> success, -1=> fail*/
int nlst()
{
struct sockaddr_in client;
struct hostent *clientAddr;
short portNum;
char cmd[STDSIZE];
int dataSockFD;
socklen_t sin_size;
if((dataSockFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket call failed!");
exit(0);
}
/* gethostname call */
if(gethostname(hPtr,STDSIZE) == -1)
printf("%s\n", strerror(errno));
/* WORKS SO FAR */
/* finding out my IP address */
if( (clientAddr = gethostbyname(hPtr)) == NULL)
{
printf("Gethostbyname error!");
exit(1);
}
// short port;
client.sin_family = AF_INET;
client.sin_port = htons(0);
client.sin_addr = *((struct in_addr *)clientAddr->h_addr);
memset(&(client.sin_zero), '\0', 8); // zero the rest
/* set sock option for port reuse */
if(setsockopt(dataSockFD, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) {
printf("setsockopt failed!");
exit(1);
}
/* attempt to bind while it fails */
if((bind(dataSockFD, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1))
{
printf("bind failed.");
exit(1);
}
/* start listening for a connection from server-DTP */
if(listen(dataSockFD, QUEUE) == -1)
{
printf("%s\nE:",strerror(errno));
exit(1);
}
sin_size = sizeof(client);
if(getsockname(dataSockFD,(struct sockaddr *)&client, &sin_size) == -1)
{
printf("getsockname failed.");
exit(1);
}
// put it in
int IP = *( (int *)(clientAddr->h_addr_list[0]));
IP = htonl(IP);
sprintf(cmd,"PORT %d,%d,%d,%d,%d,%d\r\n",
(IP & 0xFF000000) >> 24 ,
(IP & 0x00FF0000) >> 16 ,
(IP & 0x0000FF00) >> 8 ,
(IP & 0x000000FF) ,
(client.sin_port & 0xFF00) >> 8 ,
(client.sin_port & 0x00FF));
char *c;
char cmd1[STDSIZE];
// send PORT command
c = cmd;
write(sockFD,c, strlen(c)); // sending PORT command
if(receive() == 0) { }
// if NLST
strcpy(cmd1, "NLST \r\n"); <--- issues at this point!!!!
c = cmd1;
write(sockFD,c,strlen(c));
if(receive() == 0) {
int dataFD;
if((dataFD = accept(dataSockFD, NULL, NULL)) == -1)
{
printf("%s\n",strerror(errno));
}
else
printf("Accepted from server!");
char l;
if(read(dataFD, l, 1) > 0) // test if anything has been written to socket by server
printf("%c\n",l);
}
else
printf("something wrong with 'NLST' command");
// receive again... after reading directory...
if(receive() == -1) {
printf("receive error 2\n");
exit(0);
}
return 1;
}