Skip to content

Instantly share code, notes, and snippets.

@tejasri-v
Last active December 31, 2021 23:18
Show Gist options
  • Save tejasri-v/f1741e7d29558aa9be7efcf84b00c155 to your computer and use it in GitHub Desktop.
Save tejasri-v/f1741e7d29558aa9be7efcf84b00c155 to your computer and use it in GitHub Desktop.
Lab6-Part1
Part 1: mdb-lookup-server using sockets API
-------------------------------------------
Now that you learned how to use sockets API, it's time to implement a
real mdb-lookup-server that does not rely on netcat tool.
Your job is to write mdb-lookup-server.c, a program that does the same
thing as mdb-lookup.c from lab 4, except that it communicates with the
client via a socket rather than standard I/O streams.
You start the mdb-lookup-server as follows:
$ ./mdb-lookup-server my-mdb 8888
where my-mdb is the database file name and 8888 is the port number
that server should listen on. You can use netcat to connect to the
server and use the lookup service.
For this part, it's okay for the server to handle only a single client
at a time, so you don't need to fork().
This part is an exercise in combining existing code to make something new.
There is actually very little code you need to write. Basically, you
combine mdb-lookup.c from lab 4 solution with the boilerplate TCP server
code we studied in class. Here is how:
- Every time you get a socket from accept(), you basically run the code for
mdb-lookup. That is, you open the database file, read all records into
memory, run the lookup loop, and finally clean up resources when the
client is done using the lookup service. When you're done with mdb-lookup
code, you will go back to accept() in order to service the next client.
The main thing you need to do is to convert the mdb-lookup code to
read and write using the socket rather than stdin and stdout.
- For reading, the easiest thing to do is to wrap the socket file descriptor
with a FILE*, so that we can leave the fgets() code alone. fdopen() does
exactly that:
FILE *input = fdopen(socket_descriptor, "r");
will give you a FILE* that you can use in place of stdin.
When you're done, you should fclose(input), which will close the
underlying socket for you.
- For output, you need to use send() instead of printf(). Here, the
easiest thing to do is to use snprintf() to first print to a char
array and then send() what you just printed. Note that, on success,
snprintf() returns the number of characters printed.
We will use this mdb-lookup-server in lab 7, where we write a web
server which can not only serve static HTML pages, but also serve
mdb-lookup results to web browsers. In order to use mdb-lookup-server
in conjunction with a web server in lab 7, we need to do two things
when we write mdb-lookup-server now:
- Do NOT send the "lookup:" prompt to the client. Simply read the
input line (which contains the search word) from the socket, send
all the search result lines to the socket, and finally send a blank
line to the socket. The blank line at the end is important: the web
server will use it to determine the end of a search result.
- Add the following lines in the beginning of your main():
// ignore SIGPIPE so that we don't terminate when we call
// send() on a disconnected socket.
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
die("signal() failed");
#
# Makefile for lab 6, part 1
#
CC = gcc
CXX = g++
INCLUDES = -I../../lab3/solutions/part1
CFLAGS = -g -Wall $(INCLUDES)
CXXFLAGS = -g -Wall $(INCLUDES)
LDFLAGS = -g -L../../lab3/solutions/part1
LDLIBS = -lmylist
.PHONY: default
default: mdb-lookup-server
# header dependency
mdb-lookup-server.o: mdb.h
.PHONY: clean
clean:
rm -f *.o *~ a.out core mdb-lookup-server
.PHONY: all
all: clean default
Jae LeeWelcome to lab 4!Kaiheng DaiCodeforces best websiteRyan XuDo geese see godJaeHello thereJenniferhi there chloehello worldSeonghoHello world dudeNot JaeGoodbye there0ne.il42ArtemLegs feed the wolf!beansSophyaHello :)studentslove Jaegooseflap flapAna Mariahi there! :)Arthi*Hello* <3Albusnothingnngo lions:):(Tiffany Nhello dudes!Elifiahi!Shesee you later boyShrekwot r u doin in my swamtb2960Caesar mpwft uijt dmbttAdelehello.Then, Adelego easy on me.} said {} said {Margothi!Jordi AdoumieWorking on Lab 4Hehiand IRomeo, take me somewherfartfartJackFrat boykayu should try the cmd csIwhere am Idi2215parta_completegracegrace grace grace grace#constantlylostalways feeling lost andphubbyap is love ap is lifeChris DemirjianNew York is newpaulette :)hi !!!Chris LeeI LOVE AP I LOVE AP I LHunter HollandHmm Iwill this be truncHe, she said.Ruiyang HuTest input Solomonlife is a singly linkedChristopher DemEvil 3157: Farewell 315LizHope exams are going wesl5036squid gamesl5036ap testMatthew Wangbitly.com/98K8eHeasy Midterm, Easy midtermno one.i lost the gamelalala:DchaseaaaaaaaaaaaaaaaaaaaNic!Ceci n'est pas une pipeisabel[[Hyperlink Blocked]]Evil CS ProfGoodbye WorldCS MajorI got a beep-boop duecatherineyoohooooQueenPotassiumJohnnyThis here's the Duck;-;nap timeAnthonyI can't see shitxurxothis is a very long mesKyrie Irvingi hate vaccinesLeBroni hurt my thumb :(zifgo see the Lehman TriloDGCI wanna got ot to tJennifer WangNo, Johnny [2~ [C, ThiMarthaalmost faLL BreAkLindseyhelloYou got me >:(THE BITLY IS A RICKROLLRobert');DROP TABLE students;--wearenumberone (-_-) (-_-) WAKE UP WAKE UPWAKE UP WAKE UP WAKE UPbuyshibbuyshibsbuyshibbuyshibuyshibIwhat I saidAndrewGo KnicksRichardhellojiyaofried chickenrkh2128fill out the survey!lilibeep beep lettucelilipretty flowerslilidont step on the seedsBarr ShladovHello WorldCamille BeattyLadybird, labybird fly Camille BeattyThere's no place like hCamille BeattyNo more monkeysOlaKam is the best everBezaHold that airtimeKen Miura( Computernovimgit gudRichardtest testCaiwuHello! doing part(a)AlfredBrucepenguinsmile & wave boys smileAnonymoustest another languag Akash Nayarkash kash in da housr eAntonioHello thereMk it randahi eu yyyy [C [C [MonkeWhere is monke?doknei am donkeItaiHellotheohiJessetesting while in officemuad'dibanyone see dune yetDipashreyaI love dogs. JesseIt's maud'dibAryan Coding is coolJessemsg fulfilling lab4 parryanhello world :Omans( _ )!!!ii lk ike frogsPatrickHappy Fall Break! PatrickGood morning, it is 10:Pedro P. [D [D Hello World!Omer NauerAgamemnonKenobiHello there!Nauer OmerAchilleusAPLab4Steven CFall break!!Steven CWait.. I still have hwTiffany ZhongsheeeeeeeeeshJoshTed Cruz is the Zodiac AndreiButter CookiesAndreiPotato ChipsDeep Thought"Forty-two"ramobhenlo therramobit smells like updogstudentstas are awesomeWormstraws are the best!danyihello holidaydanyiit's 23:33changsucats are very cute.1234567890ABCDE1234567890ABCDEFGHIJKLMVivekhello apVivekHappy Halloween!shiba-inuto-da-moon-bruhshiba-inulets-get-a-shiba-dogajsdklfdasjklfjasdflajfklasjfklajsklfjCiroAm I late?yunkyu leehi everyoneyunkyu leegood morningWildernessabandon all hopeWildernessABANDON ALL HOPEAlfonso VUp the ChelsAlfonso VSIUUUUUUUkayahello AP!spongebobI'M READY I'M READY I'MTristanI like lerner hallTristanCats > dogsTTest message!@#RonaldoSiiiiiiiiaaSophya Wuthis is test messageJoy Fanyeehaw apsamivy=dingusruizehello worldNick KBuy GME! To the moon!shaithis is my lab4.1atest\nMattyGao Za!helloworldsdfabyeexample1example 2abd/nabbbbbb\nJoshuaHappy Halloween!Neha dark chocolate will alwmiahello everyone!!:)TiffanyHappy HalloweencmehkyawnMichelle_AhnHello everyonebutterwith breadRdOiTfOrFUnMiranda AP s is suc [3MirandaC is such a great languJoonHello guysAustin TaosquidwardJoonHello doing part aAustinhotdog != sandwichrhihirrhellohellobezaManchester United is thbezalet's go famMelanieHey ClassMelanieHappy Halloween!martinahey bestiesmartina*~ happy halloween *~YoshiI did not commit tax frthe real gabe gsoy boys to soy mennoahbyte meKranngIt is the ones known asKraangthe turtles. Attackkkk!KraangKraangKraangThe Kraang is getting tKraangtheir Kraangs handed toKraangthem by those who are nKraang not KraangKraangKraang will annihilateKraangthose who are known asKraangstudents of AP!!!KraangThen Kraang will takeKraangover New York City!!!KraangAND KRAANG SHALL BEKraangRULER OF THEM ALL!!!Kraang[laughs evilly]KraangBeware humans...for the time ofMadeline ParkHappy Halloween from PHKraangfor the time of KraangKraang IS NIGH!!!Madeline ParkhappyHalloweenFromPHLMadeline ParkcanYouCloseWindowPlsaparnahappy halloween!aparnaelection break is nicetestmeFerchosorry can't talk right dp3129Hello my pals!!!dp3129COOOOOOLshaneeeemanifesting an AP shirtshaneeeeI WILL GET ONENilson NIndiscernible frm MagicNilson NAsimov was right.Nilson NMusk IS right.Nilson NW3157 has been awesome.ihelloJoshKraang sure talks a lotjyneed to get lunchLiting HuangHow are you today?LHhelloo!!!Josh Meihello world Joshapple time Joshapple timeJosh apple time testappleabctestappleaefvMichael ScottThat's what she said!KileyHappy November!tiffany qaih yah [C [C [C [tiffany qi want cofffe ee rnrachelhello!MattGood luck on lab4Andreahello!!AndreahalloweeeenSalokayKasper HjulmandDanmark vinder VM!knock knockyeah its meDanielleHi :)DanielleI need a napMarkVery fun!MarkHello Friends!MinJohn jay > lernerKevinLerner > John Jayk KingpinIt's all about the Metsalyssahi yallalyssathis is so cool!Ananya HajraAdding to Lab4!Emily DickinsonI'm Nobody! Who are youEmily DickinsonAre you nobody, too?KennyHello there!Lance\n\nLance'\n'Lance'\0''\ \0' \0 \n [C [C [Cmaya:)michaellllbachir hay fina 10452Manuel PaezPlease Read KafkaAhmedwe are gganbuManuel PaezBayern over MilanAnimesh hi everyone :) albusLove and Peacealbusmy heart will go onalbusmay the code be with uJungsoo KimHappy Halloweekendhahahayuqwedhellotoday is MondayJanebyebyeNicoHellooo!Jorge Hernandezhello!Susannahhappy novemberSydneyIt's November!CatraHeyyy Adora ;)RahilhelloCarolinetestingcshihiDaniel Joomy password is passwordDaniel JooJae do you know korean?ameliahello world!ameliagoodbye world!KiaraHappy Halloween!Kiarawhish me luckjamiehelloooojamiethis class is hardmalikthis is my messageJoshuaSoup for every mealJoshuaHigh fiber. Low ProteinSilviaweeee! :)veeri am tiredwut's my namerihannaTheo Mackhello worldHellohiiiiBossI LOVE AP SOOOOOOO MUCH\n hello\n goodbyeChidinma MbaThanos was rightalyssahi hiYongmsgLilian I love basketballMichellehappy belated Halloweenshellap is the best classliddieaespa is in kwangyaCCHappy November!CCPumpkin >_<daniela yanohello!!daniela yanobye!shakiraspherical chickenKimiya Shahamatnever gonna give you upNik Tungaturthyncse I dnt c u,ga,ge,gnFaithHow was HalloweekendJayGreen Bubbles = BadFaith OnyechereIt'sssss party time!DanziHimaya srikanthhello there!IainHello all!Isobelstarting late is betterKam LambertHappy November!ShrekLife = OnionMichael ScottWhere are the turtles!?Cynthiayeah fall break was oveIsak HeI am sad.Samyahello friendShivI am sleepySamyasomeone get the referenRyuHADOUKEN!MarioLet's-a GO-O!YOLOI love you Jaeescobarplata o plomosoulja boyturn my swag onSarahHi have a great day!GurnoorWassupG-MoneyWas poppin Nicolas HHello Everyone!Nicolas H1234 123123123123123Nicolas HTest 123charlesi love apJuanHey AP!Jianyanghappy birthdayJianyangapapapyoungseoit's wednesdayLeonhello worldnamenamemessagemessagelinndaqunhello classMaya LetonaI like to wrestleNoah CPoopoopeepeeNoah CLab 4 part 1AMiiraJae's the bestDavid GWfall break too shortDavid GWvenmo me @leebollingerJosh Segoviahello world!JoshTest test test test tesJosh aaaabbbbccccddddeeeeffftonyhelloHo Jun YiHelloArcher StauntonheyNick FeibelThe cake is a lie.Nick FeibelBut then again, I like PikachuPika Pika ChuuDHtry part 1 dudeYuhanhahahahaha!DHsecond try dudeRuthu can do it guys!Olivia Rodrigogood 4 uAnanya Gfinished part1a!!cindythis msg board is cuteeRaven Rothkopfwhoop whoopEVgood soup listestingmw11823chilly weather in nycEthan Zhanghello worldAmirlisten to belowblack kray alicia key$Amirmy schtommy hurt Lauren Calvinmonkey see, monkey doOrli :)hiiiiyoOrlilol this is cuteLauren Calvinspending most of life iYilong XuI love MSG!JaeNo final examzifdfasdfadsfaRyan GrossmannHey 3157!steventestJayjae is awesomePenguinLeetcode!KangarooJohn Jae > John Jay Yvonne My message is so SheNAHCostanzahey ap!Huailing ChenjfdjkshfdklChris SHello, World!Chris S!dlroW ,olleHhydisowned by lulaoshiHanyi YuhelloWAWAWAWOHOHOHOHOHOGabriel FThis is my message.Micheal DanziI suck at clash royaleWalter WhiteI shouldve studied csjonned nedzynedapexSinnermanWhere you gonna run toJokermanWhat good will it do?NestaThese songs of freedomAruj JainWhat even is a databaseRNG-MingEDG wins S11!!!!!sldtrywskjdfprog1Hello World!Lauren Cdo what you wantIzzyMets are better than YaAruj Jaintesting testingChristopher Marnew york city is super Christopher Marmy favorite fruit is apgoosegoosequackadoodlegoosegoose2QUACKVictorHello fellow sinnersVoicesI LOVE CS I LOVE CSfreddown with metaechoecho echo echoduckquackJohnShawhow ya doinJohnShawhello theremirahtestmirahcoffeeChristopherCoxwhyisCalanguage [D MayHello there!MayThis is my second msgMaster YiI was in alphaaaabruh lmaotarahi!!OforiwaaI come in peaceduckquackleelahello hello!kanyedonda donda doooonnnndalilydamnnn, fall break is odrakeAP, do you love meYeDondaaaaaaoforiwaaok bye:)ChuqiHello!Elvina Wibisonowinter is coming Elvina Wibisonohappy endingElvina Wibisonoanimal crossing nyahello therecodersupEve here we goEve majour r in CS!ev e e [3~or don'tDaliaChris Pratt voices meChris Prattit's a me, mariosiennawhat's up\b\b\b\b\b\b\b\YO WADDUUUPPPPPPPP . . Jennyhi :)anon:)))Michael Jan FanKenHelloAngel SanchezWassup /nPenaldo/n/ncarried by PenandezBarack \nMobambTravis Scott is \nMaoisharrymarry mevalerieCreeper, Aw Maneddystarting labhuhligmaravhihihihiYuvaltop of the mornin top oa test testagain eng eng Woah^it added "?"joejoejoejoejoejoejoejojoeywasupElikaGood Morning!KobeMambaElikaGoodnight.Eliahi !Mohanad MohamedLET'S GOOOOOOOOOOOOOOOOBillhihihihihihihhihiiihihiLivhihihihihihihhihiiihihiChrisihiiiiiiiiiiiiiiiiiiiiiinigo montoyayou kill my father.inigo montoyaprepare to die~~Leonihao worldSaulhello guysTejihello :)Tejiidk wut else to saycindyhappy thursday!gabeWOW! #505 not bad...LeohelloLeoi love waterJun bruh hellotherehitest tabh iEqualsStream Equals by Ed SheOralyI wish u joy!:(tswift10 min alltoowellDon Leemessage for part 1 aDon Leemsg for part 1 ateji^@^@^@^@^@^@LOLlolAGoodPersonHi have a bad day:)Obiwanmy father's birthday isObiwantomorrowmargie...Grace Perrinhey there!Grace Perrinwhat's up?hi1234\nMayCheckMikewhats up cs3157cowmoogoatbaaadogbarkcatmeowrae vennevermoreJoonHihitestHi APtyrell wellickbonsoir elliotcarrotvegitablehummusyum whowhorickpasta saucekane yehanh [C [Cbongomaalsgs ManuelHello APersDawsonwhy was 76 afraid of 77Dawsonbecause 77 78 79AksharaHey there!AksharaIt's coldJESUSHELP ME OH GOD. I AM DYJeannie Renhello AP!!!hagridyer a wizard harryavantikaavantikahi hello heyavantikai want to sleepnikitawho else is very tired?nikitais anyone else sad hallnikitai need a vacationThe Big CheeseCHEEEEEEESSE PLEASE!ivystack supremacynatlogsnaw weeBobBobyou fool. you absolute ./mdb-addmsg pleasechrishi therechrisdoggochriswhat does the fox say?deezO_Oyz3587ap is awsomecolumbia university Sarah Shenhi there :DIsak HeI am Happy.jeff bezosi am richAliceHi how are youSchuylerinsert text hereDiakovathis is my last nameBillbrown cowSchuyrbi love cowsayBillwhite cowBillyellow cowxueheng pengmvpross gellerwe were on a break!JustinwelpJonathan is this working?Jiang GuanI LOVE THIS CLASSJiang Guan4 more labs and we are Jiang Guanwinter is comingThat's what she!Joshhahahahahahfahadcolumbia > stanfordAmmranHabari gani?Michael MondayEveryone in America is Michael Mondaycalled Michael :)WenhanHi thereWenhanByeHo Jun YiSaying Hi againKevinMyuhh get into itAhmadI finished Lab 4!Ahmadi crycz2416:DAndrewHelloStpid pplwhaaaat?Kimberlyi am hungryMelHi everyone AP is cool!ericwdo geese see godEvanHello Worlddavid\ntestdavid \n test \n testheyPipermeowal:)B)Kathycoffeeeeeedomleetrue Monica BBoba is LI [C [Cf [CEithanI love APMonica BIt's Li [CfeEithanI love SGalushi love apMonicaughMonicaso tired :(AntonioHELLO THERE!Antonioi have a pet squirrelsomeonelearned a lot hereqoioifweioqhiofewjoifjeoijwoiwejiofjewBarr ShladovHeyPhudis [C HIT THE TWCHO> [C [PHUDIS DAWIEANGWELCOME TO TWECHO>C$$$$\noff ofouchwoei owie$$$$\noofc ouchowie\0okElonJeff who?MaxI don't Know testHarveyI want to have a coffeeSilviaAP is funMichaelmake AP harder plsMoth*this lantern bussin*LightingMcqueencar or life insurance?vivianim hungryvivmy friends call me vivwilliam zpart1(a)ahoy!bye bye ooooyooooobye ooooooomiranda btesting123StudyKingButler!!!AlbusWo ai ni, HuangLitingAlbusWo ai ni, ChenzixiAlbusWo ai ni, LixiaomengWo ai ni, qypumapantsCara VOhi! I'm CaraCara VoHi! I'm Caranadiiastarting lab4 super latnadiiabut I can do it!nadiiacuz i'm a STEM queenKileysmile :D\nsl50\n3\0\\n6testHaniaWorking on part 1a"cool123\n123\0Yvanstill growingTianxiaohello thank youantohelloboygugaaaatonythis is a testtonywhat are we doing herehihelloYvanLet's see how it will gRutvikWill I need to use lateRutvik Will I need late hours?LinhelloTimeexciting stuffnc2897what would be the entryVikingsscrew the Packersheyhiyayjust started lab4catmeowallen nahi first tryDave idWhy id did I start so swethaa sureshhello other humansswethaa sureshhow is it goinggodi am afraidmehungryAlexandraDog goes "woof"AlexandraCat goes "meow"AlexandraWhat does the fox say?Leonpart a answerDebisunny initDebiUFC 268 is Littsamanthadone!simonfinish your labracqueljust started lab:(racquellong night aheadde [C [C [C [CtestNicolas HAdding gm Nicolas HAdding more entriesNicolas HJust in casejera pizza pie-ajertwomewtwoooCharlesAP is my favorite classYLinserting againAndreybye bye late days!JinhyukI like sharksJinhyuk KimIt's lateAyshaCatan is funAyshaAlmost ThanksgivingTomHola amigosanikahi everyoneMiguel Taverasstream champagne problefolkloreillicit affairsredall too wellSusannah Awhat day is today? davidhello theredavid test2 i gtest hello theretest usertest statementblahtiredash ketchumgotta catch 'em allDavidhello worldBrennenWhy do I start late...ur mom [B [D [B [B [B [B [B KateHello APlia chenthis is fineEmily Emilyhave a good daymm5342Vim>EMACSSally StantonJoe and Sally ate pizzaCarly CarsonCarly went to the beachIaintestinalkennyhelloJenniferI like turtlesJae Woo LeeI like this class.Gandalfyou shall not passa horseneighmichaelhello worldDavidHello guys!IaFinal Testderekhey therefinethis is fineNicole Neilmessage from meNicole Neilmessage #2 from me!Nicole Neila third database entryRiya GuptaHow is your day going?Riya GuptaHello thereTyA little latetaylor swiftthx for including meiwhoever threw that papesuitemateshe ate other suitematemansmansswethtestSaiHelloEshanI <3 my gfNadiaSaying goodbye to my laNadiasaying bye to my late dNadiamourning my late daysi,libertineby t sturgeongodlet there be lightPJ Yootesla xs calabasasPJ Yoooh me oh mymanasidoing part1aYana BotvinnikWinter is comingBatmanProtect the city!nothingcomes to mindWalt WhitmanO Captain! My Captain!WaltSay my name.yesyesTim CookBuy MBP14!!MBP14Don't buy me!!JuanitoI need flank steaksYouhuanhola amigos ruizesecond msgziyao iamzzyYanxi ChenHi thereNarjesit's my birthday!!JungIm lateJung HeoI'm late ver2Mr. BeanA British sitcom createPikachuPika pikaPhineas FlynnI know what we're goingBriannaBarrowstrawberry pieaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaatestesthipart1placing recordthamidbro my code dont work wriahello, i am using my laCarrolhellokutayno student, no crypersonhelloTestTestJoshuaisImademdbAddintoa server!IamtheAP godthisis post 799800800!hitestinghyyhililihi nikililinia, i love uRavenHello Shade :)ravenhiii lauryn :DhichewbaccaahhhhhhhhPiperi ate four piesnnnnkk
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "mylist.h"
#include "mdb.h"
int loadmdb(FILE *fp, struct List *dest)
{
/*
* read all records into memory
*/
struct MdbRec r;
struct Node *node = NULL;
int count = 0;
while (fread(&r, sizeof(r), 1, fp) == 1) {
// allocate memory for a new record and copy into it the one
// that was just read from the database.
struct MdbRec *rec = (struct MdbRec *)malloc(sizeof(r));
if (!rec)
return -1;
memcpy(rec, &r, sizeof(r));
// add the record to the linked list.
node = addAfter(dest, node, rec);
if (node == NULL)
return -1;
count++;
}
// see if fread() produced error
if (ferror(fp))
return -1;
return count;
}
void freemdb(struct List *list)
{
// free all the records
traverseList(list, &free);
removeAllNodes(list);
}
static void die(const char *s) { perror(s); exit(1); }
int main(int argc, char **argv)
{
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
die("signal() failed");
if (argc != 2) {
fprintf(stderr, "usage: %s <server-port>\n", argv[0]);
}
unsigned short port = atoi(argv[2]);
char *filename = argv[1];
int servsock;
if ((servsock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
die("socket failed");
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if (bind(servsock, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
die("bind failed");
if (listen(servsock, 1) < 0) // not sure what the queue size is bc the spec says its ok if the server only needs to handle one client at a time
die("listen failed");
int KeyMax = 5;
int clntsock;
socklen_t clntlen;
struct sockaddr_in clntaddr;
while(1) {
fprintf(stderr, "waiting for client ... ");
clntlen = sizeof(clntaddr);
if ((clntsock = accept(servsock, (struct sockaddr *) &clntaddr, &clntlen)) < 0)
die("accept failed");
fprintf(stderr, "client ip: %s\n", inet_ntoa(clntaddr.sin_addr));
//FILE *input = fdopen(clntsock, "r");
// r = recv(clntsock, buf, sizeof(buf), 0);
//mdb-lookup from lab 4
FILE *input = fdopen(clntsock, "r"); //idk if i'm supposed to use clntsock
FILE *fp = fopen(filename, "rb");
if (fp == NULL)
die(filename);
struct List list;
initList(&list);
int loaded = loadmdb(fp, &list);
if (loaded < 0)
die("loadmdb");
fclose(fp);
char line[1000];
char key[KeyMax + 1];
//printf("lookup: "); //CHANGE THIS
//fflush(stdout); //i cant tell if i need these anymore or not
char a[1000];
while (fgets(line, sizeof(line), input) != NULL) {
strncpy(key, line, sizeof(key) - 1);
key[sizeof(key) - 1] = '\0';
size_t last = strlen(key) - 1;
if (key[last] == '\n')
key[last] = '\0';
struct Node *node = list.head;
int recNo = 1;
int linelen;
int printlen;
while (node) {
struct MdbRec *rec = (struct MdbRec *)node->data;
if (strstr(rec->name, key) || strstr(rec->msg, key)) {
linelen = snprintf(a, 1000, "%4d: {%s} said {%s}\n", recNo, rec->name, rec->msg);
printlen = send(clntsock, a, linelen, 0);
if(linelen != printlen)
fprintf(stderr, "ERROR: send failed \n");
}
node = node->next;
recNo++;
}
linelen = snprintf(a, 1000, "\n");
printlen = send(clntsock, a, linelen, 0);
if(linelen != printlen)
die("send failed");
//printf("\nlookup: ");
//fflush(stdout);
}
if (ferror(input))
die("input");
freemdb(&list);
//end of mdb lookup
}
}
/*
* mdb.h
*/
#ifndef _MDB_H_
#define _MDB_H_
struct MdbRec {
char name[16];
char msg[24];
};
#endif /* _MDB_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment